Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Unittest NLog messages
using System.Linq;
using NLog;
using NLog.Targets;
using NUnit.Framework; // Using NUnit but any other unit test framework will do
namespace com.github.gist.coenm.Test
{
public class Xyz
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public Xyz()
{
Logger.Debug(() => "starting with.. aldsfkjdslfkja l <substring> sdfkj;lkdsfja s;lkfj ends with");
}
}
public class XyzTest
{
private MemoryTarget logTarget;
[SetUp]
public void SetUp()
{
ReInitializeLogTarget(LogLevel.Debug);
}
[TearDown]
public void TearDown()
{
DisposeLogTarget();
}
[Test]
public void TestAbc()
{
//arrange
//act
var sut = new Xyz();
//assert
Assert.That(logTarget.Logs.Count, Is.EqualTo(1));
Assert.That(logTarget.Logs.First(), Is.StringContaining("substring"));
Assert.That(logTarget.Logs.First(), Is.StringStarting("starting with.."));
Assert.That(logTarget.Logs.First(), Is.StringEnding("ends with"));
}
private void DisposeLogTarget()
{
if(logTarget != null)
logTarget.Dispose();
}
private void ReInitializeLogTarget(LogLevel logLevel)
{
DisposeLogTarget();
logTarget = new MemoryTarget { Layout = "${message}" };
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(logTarget, logLevel);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.