[英]How to unit test logging into log4net using C#
I need to test if a message is correctly logged into log.net.我需要测试消息是否正确登录到 log.net。
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 log.net.我需要另一种测试方法来了解Logger.Error()
中的消息是否正确登录到 log.net。
I don't know where to start.我不知道从哪里开始。
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());
}
I am not familiar with log.net, but I think you can use an interface for Logger.我不熟悉 log.net,但我认为您可以使用 Logger 的接口。
If you add a Logger instance to the constructor, you are able to add a Mock of ILog.如果将 Logger 实例添加到构造函数,则可以添加 ILog 的 Mock。 Just Assert that mock to check the messages.只需断言该模拟即可检查消息。
private static readonly log4net.Ilog _logger;
public Cut (log4net.ILog logger){
_logger = logger;
}
public bool load(string fileName) {
if (File.Exists(fileName))
return true;
_logger.Error("file does not exist");
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.