I am writing a class to help me unit test my code. It looks like this:
/// <summary>
/// Wrapper for the LogManager class to allow us to stub the logger
/// </summary>
public class Logger
{
private static ILogger _logger = null;
/// <summary>
/// This should be called to get a valid logger.
/// </summary>
/// <returns>A valid logger to log issues to file.</returns>
public static ILogger GetLogger()
{
if (_logger == null)
_logger = LogManager.GetLogger("logger");
return _logger;
}
/// <summary>
/// This is used by unit tests to allow a stub to be used as a logger.
/// </summary>
/// <param name="logger"></param>
/// <returns></returns>
public static ILogger GetLogger(ILogger logger)
{
_logger = logger;
return _logger;
}
}
The second method is for unit testing only. I never intend to have it called in my production code.
Is this bad practice? Should I find another way that does not do this?
It often makes sense to write the test first and then write as much code as needed to allow the test to pass. Doing this moves towards a practice known as Test-Driven Development (TDD). Bluefruit uses a lot of TDD because it helps us to build the right product without waste and redundancies.
Tightly coupled code is extremely hard to unit test (and probably shouldn't be unit tested - it should be re-factored first), because by definition unit tests can only test a specific unit of something. All calls to databases or other components of the system should be avoided from Unit Tests because they violate this.
Code coverage is calculated for a file based on the unit tests that SUCCESSFULLY passed. After all the unit tests are run you are able to see either in your browser the exact lines in your code that are being executed or right in your terminal.
In my opinion yes, this is a bad practice. Unit testing is meant to test implementation of your code, not really to influence it. In some cases I've found it practical to organize my code/methods in a manner to make it more easily/thoroughly tested, but writing code in a class being tested for specific use in testing is a different story.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With