2011-12-04 40 views
3

在下面的測試中,如果它進入catch塊,我想表明測試已通過。如果catch塊被繞過,我想測試失敗。明確設置測試通過/失敗?

有沒有辦法做到這一點,或者我缺少測試應該如何構造的觀點?

[TestMethod] 
public void CommandExecutionWillThrowExceptionIfUserDoesNotHaveEnoughEminence() 
{ 
    IUserCommand cmd = CreateDummyCommand("TEST", 10, 10); 
    IUser user = new User("chris", 40); 

    try 
    { 
     cmd.Execute(user); 
    } 
    catch(UserCannotExecuteCommandException e) 
    { 
     //Test Passed 
    } 

    // Test Failed 
} 
+1

'CommandExecutionWillThrowExceptionIfUserDoesNotHaveEnoughEminence'? – Dani

+1

http://stackoverflow.com/questions/933613/c-how-do-i-use-assert-unit-testing-to-verify-that-an-exception-has-been-thro – BentOnCoding

回答

5

聲明測試扔UserCannotExecuteCommandException,這種情況發生時,測試會成功

[ExpectedException(typeof(UserCannotExecuteCommandException))] 
+0

但是,測試也是如果異常是*不被拋出則成功?如果沒有拋出異常,則OP需要測試失敗。 – Cameron

+0

不,它不會 –

+0

感謝你。如何阻止Visual Studio在拋出實際異常時停止執行測試?例如,我必須在測試繼續之前按F5/Continue,並且可以標記爲已通過。 – Chris

5

我傾向於當我有一個類似的情況下使用此模式:

// ... 
catch (UserCannotExecuteCommandException e) 
{ 
    return; // Test Passed 
} 

Assert.Fail(); // Test Failed -- expected exception not thrown 
0

我會建議使用Assert.Throws()方法:

Assert.Throws<UserCannotExecuteCommandException>() => cmd.Execute(user)); 

Id可以完成您所需的一切。它期望在執行cmd.Execute()方法時拋出UserCannotExecuteCommandException類型的異常,否則將自動標記測試失敗。