2013-02-13 51 views
3

我目前正在單元測試,發送無效表單集合數據時發生錯誤。單元測試控制器中拋出的異常

唯一的例外是HttpPost指數ActionResult的方法(如下所示)中拋出:

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Index(FormCollection formCollection, PaymentType payType, string progCode) 
    { 
     ActionResult ar = redirectFromButtonData(formCollection, payType, progCode); 

     if (ar != null) 
     { 
      return ar; 
     } 
     else 
     { 
      throw new Exception("Cannot redirect to payment form from cohort decision - Type:[" + payType.ToString() + "] Prog:[" + Microsoft.Security.Application.Encoder.HtmlEncode(progCode) + "]"); 
     } 
    } 

到目前爲止,我已經寫了一個測試,成功擊中異常(我已經啓用代碼覆蓋率,我已經驗證這一點正在使用,看看每個單獨的測試正在執行什麼代碼),但目前測試失敗,因爲我還沒有定義一種測試方法,已拋出異常,此測試的代碼可以在下面找到:

[TestMethod] 
    public void Error_Is_Thrown_If_HVM_FormCollection_Data_Is_Incorrect() 
    { 
     var formCollection = new FormCollection(); 
     formCollection.Add("__RequestVerificationToken", "__RequestVerificationToken"); 
     formCollection.Add("invalid - invalid", "invalid- invalid"); 


     var payType = new PaymentType(); 
     payType = PaymentType.deposit; 

     var progCode = "hvm"; 

     var mocks = new MockRepository(); 

     var httpRequest = mocks.DynamicMock<HttpRequestBase>(); 
     var httpContext = mocks.DynamicMock<HttpContextBase>(); 
     controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), controller); 
     mocks.ReplayAll(); 

     httpRequest.Expect(r => r.Url).Return(new Uri("http://localhost:8080/hvm/full/self/")).Repeat.Any(); 

     httpContext.Expect(c => c.Request).Return(httpRequest).Repeat.Any(); 

     var result = controller.Index(formCollection, payType, progCode); 
    } 

我看過使用[ExpectedException(typeof(Exception)]註釋可以在這種情況下使用?

+0

heya,您使用的是哪種版本的鼻假手術? – bas 2013-02-13 14:43:27

+0

其版本3.6.0.0 – CryoFusion87 2013-02-13 14:45:58

+0

hmm,ExpectedException可能是MStest的錯誤。 Nunit支持它更好。有沒有MStest的原因,或者你可以切換到Nunit沒有問題? – bas 2013-02-13 14:46:18

回答

2

我冒昧地改變你的測試代碼,稍微符合rhino-mocks的最新功能。它不再需要創建MockRepository,您可以使用靜態類MockRepository並致電GenerateMock<>。我還將您的SuT(系統在測試中)實例化爲以下的您的嘲笑規範。 (我對Nunit的使用經驗比使用MSTest更好,主要是因爲Nunit的發佈頻率更高,功能更可靠,再次,不確定它是否適用於TFS,但不應該很難找到)。

[Test] // Nunit 
[ExpectedException(typeof(Exception)) // NOTE: it's wise to throw specific 
// exceptions so that you prevent false-positives! (another "exception" 
// might make the test pass while it's a completely different scenario) 
public void Error_Is_Thrown_If_HVM_FormCollection_Data_Is_Incorrect() 
{ 
    var formCollection = new FormCollection(); 
    formCollection.Add("__RequestVerificationToken", "__RequestVerificationToken"); 
    formCollection.Add("invalid - invalid", "invalid- invalid"); 

    var payType = new PaymentType(); 
    payType = PaymentType.deposit; 

    var progCode = "hvm"; 

    var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); 
    var httpContext = MockRepository.GenerateMock<HttpContextBase>(); 

    // define behaviour 
    httpRequest.Expect(r => r.Url).Return(new Uri("http://localhost:8080/hvm/full/self/")).Repeat.Any(); 
    httpContext.Expect(c => c.Request).Return(httpRequest).Repeat.Any(); 

    // instantiate SuT (system under test) 
    controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), controller); 

    // Test the stuff, and if nothing is thrown then the test fails 
    var result = controller.Index(formCollection, payType, progCode); 
} 

和MStest幾乎相同的處理,除了你需要定義預期的異常多一點oldskool。 Assert exception from NUnit to MS TEST

[TestMethod] // MStest 
public void Error_Is_Thrown_If_HVM_FormCollection_Data_Is_Incorrect() 
{ 
    try 
    { 
     var formCollection = new FormCollection(); 
     formCollection.Add("__RequestVerificationToken", "__RequestVerificationToken"); 
     formCollection.Add("invalid - invalid", "invalid- invalid"); 

     var payType = new PaymentType(); 
     payType = PaymentType.deposit; 

     var progCode = "hvm"; 

     var httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); 
     var httpContext = MockRepository.GenerateMock<HttpContextBase>(); 

     // define behaviour 
     httpRequest.Expect(r => r.Url).Return(new Uri("http://localhost:8080/hvm/full/self/")).Repeat.Any(); 
     httpContext.Expect(c => c.Request).Return(httpRequest).Repeat.Any(); 

     // instantiate SuT (system under test) 
     controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), controller); 

     // Test the stuff, and if nothing is thrown then the test fails 
     var result = controller.Index(formCollection, payType, progCode); 
    } 
    catch (Exception) 
    { 
     Assert.Pass(); 
    } 
    Assert.Fail("Expected exception Exception, was not thrown"); 
} 

如果你有這部分的工作,你可以通過提供的鏈接重構它更好的可重用性。

+0

對於'MsTest'測試,只有可能會在try塊中拋出異常的調用可能會更清晰一些? – levelnis 2013-02-13 15:10:50

+0

爲項目的下一次迭代我將進行大量的重構,因此無論如何可能會考慮移動到NUnit,我打算對可能使用重定向處理錯誤的方式進行一些更改,以便它轉發到自定義錯誤視圖而不是拋出異常。我有另外兩個基於MVC 4的項目,它使用這種方法,並且它更容易測試 – CryoFusion87 2013-02-13 15:21:32

+0

對我來說,它表示沒有用於** MSTest **的'Assert.Pass()'! – Ciwan 2017-03-02 10:41:02

0

測試這個最簡單的方法是將調用包裝在try-catch中並在catch塊執行時設置布爾變量。例如:

var exceptionIsThrown = false; 
ActionResult result; 
try 
{ 
    result = controller.Index(formCollection, payType, progCode); 
} 
catch(Exception) 
{ 
    exceptionIsThrown = true; 
}