Today I though it would be nice to see what my code was logging during my unit tests, and I didn't want to dig through a log file to find the log from one specific test. Since the unit test runner is a different executing assembly than my web project, it can have it's own configuration for logging separate from the application. Knowing this, I should be able to set up this new logging behavior for my tests without changing anything in my main project's configuration.
So what makes it possible to log messages from Common.Logging to the standard unit test output?
- Anything written to Console.Out during a unit test will get captured in the unit test Output.
- Common.Logging ships with a built-in Console.Out logger adapter that we can use without requiring a larger logging framework.
- The code being tested should be doing its logging through the Common.Logging log methods.
- Using NuGet, install the Common.Logging package into your unit test project
- In the unit test project's App.Config file, add the necessary XML to configure the console logger (See XML snippet below)
- Run your unit test(s)
- See the log messages captured during each test in your test output:
And of course, let's not forget the code and configuration details:
This file contains 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
<configuration> | |
<configSections> | |
<sectionGroup name="common"> | |
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" /> | |
</sectionGroup> | |
</configSections> | |
<common> | |
<logging> | |
<factoryAdapter type="Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter, Common.Logging"> | |
<arg key="level" value="TRACE" /> | |
<arg key="showLogName" value="true" /> | |
<arg key="showDataTime" value="true" /> | |
<arg key="dateTimeFormat" value="HH:mm:ss.fff" /> | |
</factoryAdapter> | |
</logging> | |
</common> | |
</configuration> |
This file contains 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
public int AddIntegers(int a, int b) | |
{ | |
var log = LogManager.GetLogger("LoggingTo.UnitTestOutput.Demo"); | |
log.DebugFormat("Adding integers {0} and {1}...", a, b); | |
int result = (a + b); | |
log.DebugFormat("Sum = {0}", result); | |
return result; | |
} | |
[TestMethod] | |
public void AddIntegersTest() { | |
int expected = 22; | |
int actual = AddIntegers(10, 12); | |
Assert.AreEqual(expected, actual); | |
} |