2015-08-24 26 views
1

我有一個窗口窗體和一個按鈕,我試圖用codedUitest來測試它。如果引發任何異常,我希望測試失敗,但在測試類中它不會捕獲異常。如何捕獲由另一個類拋出的測試類中的異常?

這裏是我的代碼:

public void button1_Click(object sender, EventArgs e) 
{ 
    double[] dummy = new double[1]; 
    int i = 1; 

    if (i > 0) 
    { 
     throw new System.IndexOutOfRangeException("index parameter is out of range.");  
    } 
    else 
    {    
     dummy[i] = 6; 
    } 
} 

的測試方法是:

public void CodedUITestMethod1() 
{ 
    try 
    { 
     this.UIMap.TryBtn1(); 
    } 
    catch (IndexOutOfRangeException) 
    { 
     Assert.Fail(); 
    } 
} 
+2

看到這個帖子在單位醒目異常測試 http://stackoverflow.com/questions/933613/how-do-i-use-assert-to-verify-that-an-exception-has-been-拋出 – Prashant

+0

你使用什麼單元測試框架? – xeraphim

+0

http://stackoverflow.com/questions/8381042/catch-an-exception-thrown-by-another-form是好的,但我想在應用程序中使用它包含很多方法,它沒有意義添加每個方法的try catch塊,我使用.NET框架4.5 –

回答

0

你寫一個集成測試。

免責聲明:我是一個網頁開發人員 - 所以我必須假設這和使用像selenium這樣的瀏覽器驅動程序相似。

所以你在做什麼是告訴UI驅動程序點擊按鈕。這運行的代碼,但它不會在測試環境運行它。您的測試只能訪問UI。

爲了檢測錯誤是否已經被拋出,我想你將不得不檢查UI來查看彈出窗口是否已經出現。

如果你想測試的方法(這可能是最好的取決於你的情況),你可以使用NUnit和Moq。

using System; 
using Moq; 
using NUnit.Framework; 

namespace Tests 
{ 
    [TestFixture] 
    class Tests 
    { 
     [Test] 
     public void Throws() 
     { 
      var sender = new Mock<object>(); 
      var args = new Mock<EventArgs>(); 

      Assert.Throws<IndexOutOfRangeException>(() => button1_Click(sender.Object, args.Object)); 
     } 

     public void button1_Click(object sender, EventArgs e) 
     { 
      double[] dummy = new double[1]; 
      int i = 1; 

      if (i > 0) 
      { 

       throw new System.IndexOutOfRangeException("index parameter is out of range."); 
      } 
      else 
      { 
       dummy[i] = 6; 
      } 

     } 
    } 
} 
0

您可以將[ExpectedException(typeof(IndexOutOfRangeException))]屬性添加到您的TestMethod。看看MSTest Exception Handling