NUnit&测试log4net动态日志文件的位置

时间:2011-09-30 12:27:42

标签: c# nunit log4net

我正在编写一个应用程序,用户可以在其中更改(在运行时)存储log4net日志的目录。目录字符串存储在app.config中 当我想测试是否使用NUnit在正确的目录中创建日志文件时,不会创建日志文件(和相应的目录)。
在网上查找此问题时,我读到NUnit会停止日志记录,因为它使用log4net本身。提供的示例告诉您创建一个额外的.config(Test.config),它还包含log4net部分并在测试类中加载配置,我这样做了。
使用单元测试时仍然没有创建日志文件 启动应用程序时,将按原样创建日志文件。

设置日志目录的方法:

public void MyMethod()
    {
        string logDirectory = app.Settings["LogDirectory"].Value;
        //assure that the file name can be appended to the path
        if (!logDirectory.EndsWith(@"\"))
        {
            logDirectory += @"\";
        }

        //find the rolling file appender and set its file name
        XmlConfigurator.Configure();
        Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
        foreach (IAppender appender in hierarchy.Root.Appenders)
        {
            if (appender is RollingFileAppender)
            {
                RollingFileAppender fileAppender = (RollingFileAppender)appender;
                string logFileLocation = string.Format("{0}Estimation_Protocol_{1}.txt", 
                                                       logDirectory, EstimatorHelper.SoftwareVersionAndDateTime());
                fileAppender.File = logFileLocation;
                fileAppender.ActivateOptions();
                break;
            }
        }
        log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        log.Debug("Logging directory & file name set.");
    }

测试类:

class EstimatorTests
{
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    public EstimatorTests()
    {
        FileInfo fileInfo = new FileInfo(@"%property{LogName}");
        log4net.Config.XmlConfigurator.Configure(fileInfo);
    }
    [Test]
    public void TestLoadInputPaths()
    {
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        AppSettingsSection app = config.AppSettings;
        string time = DateTime.Now.Ticks.ToString();
        app.Settings["ProcessingProtocolDirectory"].Value = "C:\\thisFolderDoesntExist" + time;

        Form mainForm = new Form();
        Form.MyMethod();
        Assert.IsTrue(Directory.Exists("C:\\thisFolderDoesntExist" + time));
        //this assert fails!
    }
}

log4net config:

<configSections>
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString" value="%property{LogName}" />
    <appendToFile value="true"/>
    <rollingStyle value="Size"/>
    <maxSizeRollBackups value="5"/>
    <maximumFileSize value="10MB"/>
    <staticLogFileName value="true"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %level %logger - %message%newline%exception%newline"/>
    </layout>
  </appender>
  <root>
    <level value="DEBUG"/>
    <appender-ref ref="RollingFileAppender"/>
  </root>
</log4net>

1 个答案:

答案 0 :(得分:0)

我没有对其进行测试,但我认为您需要删除XmlConfigurator.Configure();中对MyMethod的调用,因为这会覆盖您在测试类中执行的配置。