Created
April 16, 2020 02:03
-
-
Save cyberhck/e142b7b94fd939691f67a6d3342094b1 to your computer and use it in GitHub Desktop.
Demonstration of bad code, and even worst way of testing bad code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Micro.Starter.Api { | |
public interface IService { | |
string Greet(string name); | |
} | |
public class Service : IService { | |
public string Greet(string name) { | |
return $"Hello {name}"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 theService
implementation ofIService
, 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?