C# log4net 和 nunit 测试,最基本的例子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11041502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
log4net and nunit tests, most basic example
提问by panjo
I want to try log some app messages from my app. In this very situation I just want to force nunit to work with log4net. I found some example here http://www.ofconsulting.com/PublicPortal/ofc-tech-blog/92-configure-log4net-with-nunit.html.
我想尝试从我的应用程序中记录一些应用程序消息。在这种情况下,我只想强制 nunit 使用 log4net。我在这里找到了一些例子http://www.ofconsulting.com/PublicPortal/ofc-tech-blog/92-configure-log4net-with-nunit.html。
log4net is confugured in app.config like this:
log4net 在 app.config 中配置如下:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<param name="File" value="log.txt" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
</layout>
</appender>
</log4net>
And in my test code is following
在我的测试代码中如下
[TestFixture]
class DomainTests
{
protected static readonly ILog log = LogManager.GetLogger(typeof(DomainTests));
public void LoggingTests()
{
log4net.Config.XmlConfigurator.Configure();
}
[Test]
public void BasicLogTest()
{
log.Error("write my log entry already");
}
My test is passed but nothing is written inside log.txt file. What am I doing wrong?
I just want to make it as simple as possible to store messages like entering an application, exit application. Regards.
我的测试通过了,但 log.txt 文件中没有写入任何内容。我究竟做错了什么?
我只想尽可能简单地存储消息,例如进入应用程序、退出应用程序。问候。
采纳答案by Faraday
My best guess would be for you to do something like this:
我最好的猜测是让你做这样的事情:
[TestFixture]
class DomainTests
{
protected static readonly ILog log = LogManager.GetLogger(typeof(DomainTests));
public void LoggingTests()
{
log4net.Config.XmlConfigurator.Configure();
}
[Test]
public void BasicLogTest()
{
log.Error("write my log entry already");
}
[SetUp]
RunBeforeAnyTests()
{
BasicConfigurator.Configure();
}
[TearDown]
RunAfterAnyTests()
{
// ...
}
I'd also use the Log4Net.config file rather than the app.config file, it just seems cleaner. Here's an example log4net.config file:
我也会使用 Log4Net.config 文件而不是 app.config 文件,它看起来更干净。这是一个示例 log4net.config 文件:
<log4net>
<!-- A1 is set to be a LogFileAppender -->
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender, log4net" >
<param name="File" value="C:\logging\log.txt" />
<file value="c:\logging\Main" />
<appendToFile value="true" />
<datePattern value="yyyyMMdd'.log'" />
<rollingStyle value="Composite" />
<staticLogFileName value="false" />
<maxSizeRollBackups value="-1" />
<maximumFileSize value="500MB" />
<!-- A1 uses PatternLayout -->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<!-- Set root logger level to DEBUG and its only appender to LogFileAppender -->
<root>
<!--<level value="OFF" />-->
<!--<level value="FATAL" />-->
<!--<level value="ERROR" />-->
<!--<level value="WARN" />-->
<!--<level value="INFO" />-->
<level value="DEBUG" />
<!--<level value="ALL" />-->
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
回答by m0sa
The problem is that the NUnit test runner (when run from resharper in visual studio) runs the test from another folder (it shadow copies the test assembly), so the xml configuration is not available at that point unless you specify the full config path.
问题是 NUnit 测试运行程序(当从 Visual Studio 中的 resharper 运行时)从另一个文件夹运行测试(它影子复制测试程序集),因此除非您指定完整的配置路径,否则此时 xml 配置不可用。
You could of course use the basic configuration and specify the logging configuration in code, like:
您当然可以使用基本配置并在代码中指定日志记录配置,例如:
log4net.Config.BasicConfigurator.Configure(
new log4net.Appender.ConsoleAppender {
Layout = new log4net.Layout.SimpleLayout()});
You should see the log output in the test output after that.
之后您应该会在测试输出中看到日志输出。
回答by Luke Hutton
You can adjust your unit test to check for the file itself (instead of manual inspection). Notice the file path stored in environment variables. This works on TeamCity test runners as well (no need to hard code a path).
您可以调整单元测试以检查文件本身(而不是手动检查)。注意存储在环境变量中的文件路径。这也适用于 TeamCity 测试运行器(无需硬编码路径)。
Config:
配置:
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="%env{ALLUSERSPROFILE}\test.log" />
<appendToFile value="true" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<rollingStyle value="Size" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
Code:
代码:
private string _expectedFile;
[SetUp]
public void SetUp()
{
_expectedFile = Path.Combine(
Environment.GetEnvironmentVariable("ALLUSERSPROFILE"),
"test.log");
if (File.Exists(_expectedFile))
File.Delete(_expectedFile);
XmlConfigurator.Configure();
}
[Test] public void GivenLog4NetFileAppender_WhenLogInfoStringWithLog4Net_ThenWritesToDisk()
{
ILog log = LogManager.GetLogger(typeof (LoggingIntegrationTests));
log.Info("Message from test");
LogManager.Shutdown();
Assert.That(File.ReadAllText(_expectedFile),
Is.StringContaining("Message from test"));
}
回答by Mubashar
I long as i know and used log4net with nunit, i never used any config file, you just need to add following line in test class constructor
我只要我知道并使用带有 nunit 的 log4net,我从未使用过任何配置文件,您只需要在测试类构造函数中添加以下行
BasicConfigurator.Configure();
here is the full answerif you like to see the sample test class
如果您想查看示例测试类,这里是完整的答案

