This will look a bit like this
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 void DoSomething() | |
{ | |
try | |
{ | |
ReallyDoSomething(); | |
} | |
catch (Exception ex) | |
{ | |
this.logger.LogError("An error occured!", ex); | |
} | |
} |
From the outside we might not be able to test whether ReallyDoSomething has thrown an exception except if we can validate state changes done by ReallyDoSomething. And if we can't change the code much (like adding dependencies using parameters or change the return type of the method) we won't be able to write that test at all.
Another way is to use the logger to validate that.
The piece of code above use Log4Net as the logging framework and allow us to use it in our unit tests like this
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
[SetUp] | |
public void SetUp() | |
{ | |
this.memoryAppender = new MemoryAppender(); | |
BasicConfigurator.Configure(this.memoryAppender); | |
... | |
} | |
[Test] | |
public void TestSomething() | |
{ | |
... | |
// Assert | |
Assert.IsFalse( | |
this.memoryAppender.GetEvents().Any(le => le.Level == Level.Error), | |
"Did not expect any error messages in the logs"); | |
} |
Just like that we can intercept all the logged messages by our production code.
I've used this trick a few times now when other options were not available. Hope it helps.