簡體   English   中英

在單元測試中使用try / catch塊

[英]Using try/catch blocks in unit tests

使用VS的測試框架,我目前正在編寫我的測試:

[TestMethod]
public void TestSomething() 
{
    try
    {
        var someTestValue = _someTestClass.SomeTestMethod();            

        Assert.IsNotNull(someTestValue);
    }
    catch (Exception e) 
    {
        Assert.Fail(e.Message);
    }
}

我的邏輯是,如果在SomeTestMethod()拋出異常,我將立即通過Assert.Fail(e.Message)終止顯示異常消息的測試。

做事的“正常方式”是:

[TestMethod]
public void TestSomething() 
{
    var someTestValue = _someTestClass.SomeTestMethod();            

    Assert.IsNotNull(someTestValue);
}

我的方法是正確的,還是“正常方式”是正確的? 我在寫冗余代碼嗎?

我說這是多余的,是的。 如果異常是意外結果,則測試失敗。 測試框架是否以相同的方式處理是否通過拋出異常或失敗Assert而失敗。 基本上,失敗的測試是失敗的測試。

如果測試方法拋出異常的測試框架都已經失敗的考驗。 您正在添加額外的工作,沒有附加價值。

你正在編寫冗余代碼。 Test方法已經捕獲異常並且將使測試方法失敗。

如果您期望某些異常,請使用以下屬性:

[TestMethod]
[ExpectedException(typeof(//Here the exception you expect))]  <------------
public void TestSomething() 
{
//Your test code
}

這意味着如果測試拋出此異常,將返回通過測試。

如果您不去測試異常,那么請避免在測試中使用try / catch塊。 你會注意到出了問題,因為測試會失敗;)

我希望這有幫助

看本教程; 有一個使用[expectedException()]屬性的示例單元測試:[ExpectedException單元測試教程] [1]

  [1]: http://msdn.microsoft.com/en-us/library/hh694602%28v=vs.110%29.aspx#BKMK_Writing_your_tests

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM