我写了以下代码:
[TestMethod]
//[ExpectedException(typeof(UriFormatException), "url should be well formatted.")]
public void FetchHtmlContent_badUrl_throwUriFormatException()
{
HashSet<string> urls = new HashSet<string> { "ww.stackoverflow.com" };
var contextManager = new ContentManager(urls);
var content = contextManager.GetHtmlContent();
Assert.IsTrue(content.ElementAt(0).Contains("threw an exception of type 'System.UriFormatException'"));
}
contextManager.GetHtmlContent()不会抛出异常,
但是content.ElementAt(0)
抛出(正如预期的那样)
+ content.ElementAt(0) 'content.ElementAt(0)' threw an exception of type 'System.UriFormatException' string {System.UriFormatException}
如何验证content.ElementAt(0)抛出此异常
(或者我应该以其他方式验证此测试?)
答案 0 :(得分:2)
ContentManager.GetHtmlContent
方法的责任是什么?如果名称表示从URL检索HTML内容,则无效的URL是执行失败场景(方法无法按预期执行)。你有两个选择:
.GetHtmlContent
方法抛出无效的uri异常(很好地沟通会发生什么,并遵循Microsoft guidelines)null
返回.GetHtmlContent
并稍后处理请注意,返回null结果也可能用于HTML内容确实为null
的情况,因此我建议在此处抛出异常。它以更清晰的方式陈述了发生的事情。
您的测试可能如下:
[TestMethod]
[ExpectedException(typeof(UriFormatException), "url should be well formatted.")]
public void GetHtmlContent_ThrowsInvalidUriException_WhenUriIsInBadFormat()
{
HashSet<string> urls = new HashSet<string> { "ww.stackoverflow.com" };
var contextManager = new ContentManager(urls);
contextManager.GetHtmlContent();
}