【发布时间】:2016-11-28 11:10:09
【问题描述】:
为我的应用程序编写测试。想测试与异常处理的连接,现在我已经创建了可行的方法,看起来像:
[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");
}
在最终版本中,正在处理 smth 将捕获异常 - WebExeption。已经在我即将创建连接的方法中的 try / catch 块中使用它,它可以正常工作。但在我的测试中也需要它。我在想它应该看起来像:
[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 地址,这将导致 Web 异常。我怎样才能正确地写它?
【问题讨论】:
-
在我看来,您应该使用 Assert.Throws 而不是 ExpectedExceptionAttribute。 Assert.Throws 的使用使其在您期望异常的地方更加明确。您的代码应如下所示:
Assert.Throws <WebException>(() => connection.CreateConnection(...)。此外,NUnit 3.0 不正式支持 ExpectedExceptionAttribute。最后,您应该有两个独立的单元测试 - 一个用于有效连接,另一个用于无效连接。
标签: c# nunit webexception