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