2016-11-28 188 views
0

爲我的應用程序編寫測試。想測試與exeption處理連接,其工作原理和貌似現在我已經創建方法:單元測試連接/ C#

 [Test] 
     public void TestCreateConnection() 
     { 
      Connection testConnection = new Connection(); 
      connection.CreateConnection(correctURL, IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name"); 
      testConnection.CreateConnection(correctURL, IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name"); 
     } 

在finall版本上的不便,這將趕上異常工作 - WebExeption。已經在我的方法裏面的try/catch塊中創建連接,它的作用就是c。但是在我的測試中也需要它。我想它應該是這樣的:

[Test] 
     [ExpectedException(typeof(WebException))] 
     public void TestCreateConnection() 
     { 
      Connection testConnection = new Connection(); 
      connection.CreateConnection(correctURL, IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name"); 

      testCconnection.CreateConnection(correctURL, IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name"); 
      Assert.Catch<WebException>(() => connection.CreateConnection("test", IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name");); 
     } 

就像我們可以看到,我改變這是URL地址的方法的第一個參數,它會淡然網絡exeption。我怎樣才能以正確的方式寫出來?

+0

在我看來,你應該使用Assert.Throws而不是ExpectedExceptionAttribute。 Assert.Throws的使用使得它更加明確你希望發生異常的地方。你的代碼應該如下所示:'Assert.Throws (()=> connection.CreateConnection(...)'。此外,NUnit 3.0並沒有正式支持ExpectedExceptionAttribute。最後,你應該有兩個獨立的單元測試 - 一個用於有效連接,一個用於無效連接。 –

回答

0

我不認爲你測試異常的方法有什麼問題。然而,我建議你將測試分成兩個測試 - 一個用於獲得有效連接的情況,另一個用於連接不良的情況。

[Test] 
    public void WhenCorrectUrlIsPassedConnectionCreatedSuccessfully() 
    { 
     Connection testConnection = new Connection(); 
     connection.CreateConnection(correctURL, IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name"); 
    } 

    [Test] 
    [ExpectedException(typeof(WebException))] 
    public void WhenIncorrectUrlIsPassedThenWebExceptionIsThrown() 
    { 
     Connection connection = new Connection(); 
     Assert.Catch<WebException>(() => connection.CreateConnection("test", IDName + connection.ApiKey, connection.ContentType, connection.MediaType, connection.Get, false, "name");); 
    } 

這不知道你如何實現測試連接的確切細節。如果您有一些負責創建連接的內部組件,並且您的代碼是一個包裝器,那麼您應該考慮將內部組件作爲接口傳遞並嘲笑它的行爲。