我正在写一个Downloader(与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](http://stackoverflow.com/questions/11025097/untitesting-moq-method-calling-webrequest)。我认为它解释了你想要达到的目标。 – Hintham
一个问题;你为什么抓住并立即重新抛出这些例外?您的代码编写方式,此处引发的任何异常都将显示给调用者。所以我不确定是否需要对此进行单元测试 - 如果webRequest.GetResponse中出现WebException异常将会出错的情况,可以认为它是公理性的;因为那不是你控制的代码,你不需要测试它。 –
您正在使用什么版本的Visual Studio? – zaitsman