Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test & Log4net

I have unit test testing an action in my controller, the action writes to log4net.

When I run my action it works well - writes to log4net .

However , When I run the unit test - the action doesn't write to log4net but doesn't throw any exception.

Does anyone have a solution?

like image 727
ParPar Avatar asked Nov 17 '11 06:11

ParPar


People also ask

Where is unit testing done?

Unit Testing is typically performed by the developer. In SDLC or V Model, Unit testing is the first level of testing done before integration testing. Unit testing is such a type of testing technique that is usually performed by developers.

What is a unit test in school?

A unit test is an automated piece of code that invokes a unit of work in the system and then checks a single assumption about the behavior of that unit of work.

How unit testing is performed?

A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior.


1 Answers

// ARRANGE
var memoryAppender = new MemoryAppender();
BasicConfigurator.Configure(memoryAppender);

// ACT
_sut.DoWhatever();

// ASSERT - using xunit - change the expression to fit your purposes
Assert.True(memoryAppender.GetEvents().Any(le => le.Level == Level.Warn), "Expected warning messages in the logs");

You don't need to add in another layer of indirection by using a logging interface (if you don't want to). I have used the abstracted way for years, but now am moving towards just using the MemoryAppender as it is testing what is actually happening. Just be sure to .Clear() the appender after each test.

like image 176
RhysC Avatar answered Oct 21 '22 20:10

RhysC