Home > Software design >  How to unit test logging into log4net using C#
How to unit test logging into log4net using C#

Time:12-10

I need to test if a message is correctly logged into log4net.

public bool load(string fileName) {
    if (File.Exists(fileName))
        return true;
    Logger.Error("file does not exist");
    return false;
}

In my test file, I have this :

[Test Class]
public FileTest {
    private File file;
    
    [TestInitialize]
    public void Setup() {
        file = new File();
    }

    [TestMethod]
    public void ConstructorSuccessedTest() {
        Assert.IsNotNull(file);
        Assert.IsNotNull(File.Logger);
    }
}

I need another test method to know whether the message in Logger.Error() is correctly logged into log4net.

I don't know where to start.

CodePudding user response:

i found my answer :

[TestMethod]
public void LoggerIngo()
{
    var appender = new log4net.Appender.MemoryAppender();
    log4net.Config.BasicConfigurator.configure(appender);
    
    var fileLoad = file.load("file.xlsx");

    var logEntries = appender.GetEvents();
    Assert.AreEquals("file does not exist", logEntries[0].MessageObject.ToString());
}
  • Related