如何在Visual Studio单元测试中声明一个错误初始化的集合?

时间:2012-03-11 15:14:47

标签: c# visual-studio-2010 unit-testing

我写了以下代码:

[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)抛出此异常

(或者我应该以其他方式验证此测试?)

1 个答案:

答案 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();
}