Search code examples
logging.net-coremstest

How to print information in .net core test projects?


What's the standard way of printing messages in a test project?

I have an Integration test project written in MSTest and each test case contains login step and the actual call etc. I need to print some messages to console to track information like which role it login as and which url it's calling.

Ideally I want the messages to show only in Debug mode.

Currently I am using Console.WriteLine with #if DEBUG directive. Is there any better way of doing it?


Solution

  • You shouldn't need to log anything in your unit tests. The premise being that the code in the tests speak for themselves and anyone reading them can understand what is going. If you feel the need to add logging to your tests then that is a sign that your code is too complicated and needs to be refactored.

    It's a good idea to understand the principles behind SOLID principles and refactor your code to follow these "rules". I would recommend the first principle you try to follow is the Single Responsibility Principle. This should help you refactor your code to make it more testable and remove the need to add logging to your tests. (NOTE: There are other examples on the internet - the links above are just examples I found with a quick search).

    EDIT

    You could create your own logger class to wrap your Console.WriteLine(...) calls e.g.

    public static class TestLogger
    {
        public static void Log(string output)
        {
    #if DEBUG
            Console.WriteLine(output);
    #endif
        }
    }
    

    and in your test code use your class

    public class MyTests
    {
        public void FirstTest()
        {
            TestLogger.Log("Just started");
        }
    }
    

    The fact that the logger only writes to the console in debug mode is hidden from the test code and should hopefully make it a little clearer. In the future, if you want to use Log4Net or another logging library you can update your TestLogger class and, hopefully, none of your test cases need changing :-)