2013-01-23 55 views
0

我試圖驗證某些錯誤是否記錄在log4net文件中,並且發生了多少次。 我正在研究下面的代碼,它將讀取一個值,並斷言它是否正確,但是 我想查看它在日誌文件中出現的次數,如果它是真的,就會斷言它。NUNIT測試c#中的日誌文件

private string logfile; 

[SetUp] 
public void SetUp() 
{ 
    logfile = Path.Combine(
     Environment.GetEnvironmentVariable("ALLUSERSPROFILE"), 
     "test.log"); 

    if (File.Exists(logfile)) 
     File.Delete(logfile); 

    XmlConfigurator.Configure(); 
} 

[Test] public void GivenLog4NetFileAppender_WhenLogInfoStringWithLog4Net_ThenWritesToDisk() 
{ 
    ILog log = LogManager.GetLogger(typeof (LoggingIntegrationTests)); 
    log.Info("Error 2"); 

    LogManager.Shutdown(); 

    Assert.That(File.ReadAllText(logfile), 
       Is.StringContaining("Error 2")); 
} 

所以在上面的代碼中,如果錯誤2被記錄了3次比我想斷言它出現了3次。 感謝您幫助

回答

2

你可以使用一個Regex來算的次數給定的字符串在另一個字符串中出現:

[Test] 
public void GivenLog4NetFileAppender_WhenLogInfoStringWithLog4Net_ThenWritesToDisk() 
{ 
    // arrange 
    ILog log = LogManager.GetLogger(typeof (LoggingIntegrationTests)); 
    string = "Error 2"; 

    // act 
    log.Info(dataToLog); 

    // assert 
    LogManager.Shutdown(); 
    var matches = Regex.Matches(File.ReadAllText(logfile), dataToLog); 
    Assert.AreEqual(3, matches.Count); 
}