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。最后,你应该有两个独立的单元测试 - 一个用于有效连接,一个用于无效连接。 –