Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to add code just for unit testing? [closed]

Tags:

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?

like image 497
Vaccano Avatar asked Sep 02 '10 17:09

Vaccano


People also ask

Should you write unit tests before code?

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.

What makes code difficult for unit testing?

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.

Is code coverage should happen after unit testing?

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.


1 Answers

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.

like image 92
Chris Forrette Avatar answered Oct 26 '22 02:10

Chris Forrette