【发布时间】:2017-04-11 18:17:56
【问题描述】:
我正在编写一个下载器(为了玩 TDD 的乐趣),因为我有一个方法,它的职责是连接到文件。
class FileConnectorHttp : IFileConnector
{
public void ConnectToFile()
{
//creating a concrete web request here.
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(UriForTheFileToConnect);
//sending HEAD request.
webRequest.Method = "HEAD";
//other logic for connection will go here.
try
{
HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse;
}
catch (ProtocolViolationException e)
{
throw;
}
catch (InvalidOperationException e)
{
throw;
}
}
}
我写了一个测试,测试连接超时的场景。
[Test]
public void ConnectToSourceFile_ValidUri_Connection_TimeOut_Throws_WebException()
{
Uri uriForTheFileToDownload = new Uri("https://suppose/this/is/valid/url.txt");
FileConnectorHttp fileConnectorOverHttp = new FileConnectorHttp(uriForTheFileToDownload);
Assert.Throws(Is.TypeOf<WebException>(),
() => fileConnectorOverHttp.ConnectToFile());
}
所以要获得这个异常,我应该关闭我的 Wifi 连接吗?测试这种异常的有意义的方法应该是什么?
【问题讨论】:
-
看看这个post。我认为它解释了您想要实现的目标。
-
一个问题;你为什么要捕获并立即重新抛出这些异常?按照您的代码编写方式,此处引发的任何异常都会显示给调用者。所以我不确定是否需要对此进行单元测试——你可以认为如果
webRequest.GetResponse出现问题,将抛出 WebException 是不言而喻的;因为那不是你控制的代码,所以你不需要测试它。 -
您使用的是什么版本的 Visual Studio?
标签: c# unit-testing tdd nunit