Skip to content

Instantly share code, notes, and snippets.

@coenm
Created January 9, 2015 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coenm/aea282d86a6a7387411c to your computer and use it in GitHub Desktop.
Save coenm/aea282d86a6a7387411c to your computer and use it in GitHub Desktop.
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