Skip to content

Instantly share code, notes, and snippets.

@cyberhck
Created April 16, 2020 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyberhck/e142b7b94fd939691f67a6d3342094b1 to your computer and use it in GitHub Desktop.
Save cyberhck/e142b7b94fd939691f67a6d3342094b1 to your computer and use it in GitHub Desktop.
Demonstration of bad code, and even worst way of testing bad code
using System;
namespace Micro.Starter.Api {
public class BadClass {
private IService _service = new Service(); // it's a bad idea to do new inside a class, remember, new is glue
public void Greet(string name) {
Console.WriteLine(_service.Greet(name));
}
}
}
namespace Tests
{
public class BadClassTest
{
[Test]
public void TestGreetDoesNotThrowException()
{
var unit = new BadClass();
// var mock = new Mock<IService>();
// mock.Setup();
// use reflection to change the implementation under the hood,
// unit._service = mock;
Assert.DoesNotThrow(() => unit.Greet())
}
}
}
namespace Micro.Starter.Api {
public interface IService {
string Greet(string name);
}
public class Service : IService {
public string Greet(string name) {
return $"Hello {name}";
}
}
}
@cyberhck
Copy link
Author

Looking at this, it should be abundantly clear that, if you're trying to "hack" into internals to do something, then you're doing something wrong, remember, new is glue, here, your class is glued to the Service implementation of IService, there's no way to change that except doing dirty hacks like shown above.

Why is it that this in C# and many languages accepted as a bad practice, but using the following is not considered a bad pattern?

jest.mock('./getTime', () => ({
    getTime: jest.fn().mockReturnValue('mockNow')
}));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment