2016-01-04 33 views
-2

這是我在visual studio 2013中的第一個單元測試。 首先,我創建一個web應用程序,然後添加一個新項目作爲單元測試。然後在我的項目中,我添加了log4net。 一樣, Web應用程序webconfig如何在visual studio中的單元測試用例中寫入日誌文件

<log4net> 
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender"> 
    <!--<param name="File" value="LOG/Interview_LogFile.txt"/>--> 
    <file type="log4net.Util.PatternString" value="%property{LogFileName}" /> 
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> 
    <appendToFile value="true" /> 
    <rollingStyle value="Size" /> 
    <maxSizeRollBackups value="10000" /> 
    <maximumFileSize value="10MB" /> 
    <staticLogFileName value="true" /> 
    <layout type="log4net.Layout.PatternLayout"> 
    <!--<param name="ConversionPattern" value="%date [%thread] : %method %level %logger - %message%newline%exception"/>--> 
    <param name="ConversionPattern" value="%date [%thread] : %message%newline%exception" /> 

    </layout> 
</appender> 

<root> 
    <level value="ALL" /> 
    <appender-ref ref="LogFileAppender" /> 
</root> 

我的項目文件圖像project solution

enter image description here

測試用例Testcase enter image description here

這log4net的與網絡合作應用程序,但單元測試類文件不工作我能做什麼?

+0

在單元測試中使用記錄器的目的是什麼? –

+0

如果測試用例文件意味着我不需要簽入代碼。如果我指的是日誌文件意味着我可以清楚的想法 –

+2

你需要用你的測試用例代碼更新你的問題(特別是當你刪除了圖像鏈接時)。它不能被回答。使用記錄器記錄單元測試的結果忽略了測試的重點。 –

回答

0

您的記錄器配置位於web.config文件中,因此這些設置將僅在Web應用程序的上下文中可用。

運行測試項目時,它具有不同的上下文,並且它不理解web應用程序項目中存在的web.config文件。

爲了克服這個問題,你需要添加一個app.config文件到你的單元測試項目中,並在該文件中複製記錄器設置。

+0

我可以添加global.cs文件 –

+0

@MalathiLakshmi - 添加global.cs文件不會產生任何差異,事實上你不能添加一個單元測試項目,因爲它是一個類庫。只需右鍵單擊您的單元項目>>添加「應用程序配置文件」並將其命名爲例如app.config >>在'configuration'中只需複製你的log4Net配置。那麼你的代碼應該工作得很好。 – Yogi

0

當前,您有一個單元測試方法,它似乎在測試字符串變量的類型是字符串。測試失敗的唯一方法是如果它不是字符串。如果發生任何異常,您將其從測試中隱藏起來,因此測試會認爲它正確傳遞。

單元測試框架依賴於測試拋出異常或斷言失敗,以檢測失敗的測試。所以你不應該在你的代碼中有try/catch,因爲這會妨礙框架的工作。此外,該框架將記錄測試失敗並向您報告。你不應該試圖使用不同的記錄器來做到這一點。

爲了讓您的測試工作:

  1. 給它一個合適的名字。 UnitTest1沒有揭示測試的目的。
  2. 刪除try/catchlogger.***行。
  3. 設計一個合適的Assert.***,以有意義的方式測試methodobj的結果(例如,它報告有效的呼叫的成功和無效呼叫的失敗)。
0

許願自動保存單元測試「輸出」,這是通常只通過測試資源管理器窗口中可用,我覺得我有另一種解決方案,如下圖所示:

/// <summary> 
/// Test Logger. 
/// </summary> 
/// <remarks> 
/// Build unit test code as follows: 
/// <code> 
/// using TestCommon; 
/// [TestClass] 
/// public class MyTestClass { 
/// 
/// // This property & static MUST be inside your [TestClass] 
/// public Microsoft.VisualStudio.TestTools.UnitTesting.TestContext TestContext 
/// { get { return context; } 
///  set { context = value; } } 
/// private static TestContext context = null; 
/// private static TestLogger log = null; 
/// [ClassInitialize] 
/// public void Initialize() { 
///  log = new TestLogger(logFileName); // provide a path\name 
/// } 
/// 
/// [TestMethod] 
/// public void MyTest() 
/// { 
///  try { 
///   log.Open(context); 
///   ... // perform a test 
///   log.Info("time: {0} Iteration {1}", Now, i); 
///  } catch (AssertFailedException ex) 
///   log.Exception(ex); 
///   throw; 
///  } finally { 
///   log.Close(); 
///  } 
/// } 
/// </code> 
/// </remarks> 
public class TestLogger 
{ 
    private static TestContext context = null; 

    private string logfilename = null; 
    private TextWriterTraceListener writer = null; 
    private DataCollectorMessageLevel errorLevel = DataCollectorMessageLevel.Info; 

    /// <summary> 
    /// Microsoft.VisualStudio.TestTools.Common.DataCollectorMessageLevel 
    /// Levels: Error, Warning, Info (default), Data 
    /// </summary> 
    public DataCollectorMessageLevel ErrorLevel 
    { 
     get { return errorLevel; } 
     set { errorLevel = value; } 
    } 

    /// <summary> 
    /// Create the logger. Set up work in Class initializer, it should also work inside each test. 
    /// </summary> 
    /// <param name="logfile">Path to the file to log into</param> 
    public TestLogger(string logfile, bool update = true) 
    { 
     logfilename = logfile; 
     errorLevel = DataCollectorMessageLevel.Info; 
     if (!update) 
      try { System.IO.File.Delete(logfile); } catch { } 
     writer = new TextWriterTraceListener(logfilename); 
     Debug.Listeners.Add(writer); 
     Debug.AutoFlush = true; 

     if (context != null) 
     { 
      Debug.WriteLine("Test Logger: {0} - {1}", context.FullyQualifiedTestClassName, context.TestName); 
     } 
    } 

    /// <summary> 
    /// At start of a test, it logs that information 
    /// </summary> 
    /// <param name="theContext">records context to access Test Name</param> 
    public void Open(TestContext theContext) 
    { 
     context = theContext; 
     Debug.WriteLine("Test Logger: {0} - {1}", context.FullyQualifiedTestClassName, context.TestName); 
    } 

    /// <summary> 
    /// At end of a test. Best if put in a finally clause. 
    /// </summary> 
    public void Close() 
    { 
     if (context != null) 
     { 
      Debug.WriteLine("Test Ending: {0} - {1}", context.FullyQualifiedTestClassName, context.TestName); 
     } 
     Debug.WriteLine(""); 
    } 


    /// <summary> 
    /// The Logger functions use a standard string format 
    /// </summary> 
    /// <param name="format"></param> 
    /// <param name="parameters"></param> 
    public void Data(string format, params object[] parameters) 
    { 
     if (errorLevel > DataCollectorMessageLevel.Data) return; 
     Debug.WriteLine(format, parameters); 
    } 
    public void Info(string format, params object[] parameters) 
    { 
     if (errorLevel > DataCollectorMessageLevel.Info) return; 
     Debug.WriteLine(format, parameters); 
    } 
    public void Warning(string format, params object[] parameters) 
    { 
     if (errorLevel > DataCollectorMessageLevel.Warning) return; 
     Debug.WriteLine(format, parameters); 
    } 
    public void Error(string format, params object[] parameters) 
    { 
     if (errorLevel > DataCollectorMessageLevel.Error) return; 
     Debug.WriteLine(format, parameters); 
    } 
    /// <summary> 
    /// Able to include the Assert error message in the log 
    /// </summary> 
    /// <param name="ex">ex.Message is the Assert message, ex.ToString includes the call stack</param> 
    public void Exception(Exception ex) 
    { 
     if (ex is AssertFailedException) 
     { 
      // ex.Message is only the Assertion text 
      Debug.WriteLine(String.Format("{0}", ex.ToString())); 
     } 
     else 
     { 
      Debug.WriteLine(string.Format("{0}", ex.ToString())); 
     } 
    } 
} 

,如果你運行或工作調試測試我只希望早些時候知道上下文,以便輸出可以放在\ TestResults \目錄中。

相關問題