C# 如何在visualStudio单元测试中断言错误的初始化集合?

C# 如何在visualStudio单元测试中断言错误的初始化集合?,c#,visual-studio-2010,unit-testing,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.c

我编写了以下代码:

[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'"));
}
如何验证内容。ElementAt(0)引发此异常


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

ContentManager.GetHtmlContent方法的职责是什么?若顾名思义,从URL检索HTML内容,那个么无效的URL就是执行失败的场景(方法不能做它应该做的事情)。你有两个选择:

  • .GetHtmlContent
    方法引发无效的uri异常(很好地传达所发生的情况,并遵循该方法)
  • .GetHtmlContent
    返回
    null
    ,稍后再处理
请注意,当HTML内容确实为
null
时,也可以使用返回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();
}
[TestMethod]
[ExpectedException(typeof(UriFormatException),“url应具有良好的格式。”)]
public void GetHtmlContent通过InvaliduriException\u WhenUriIsInBadFormat()时
{
HashSet url=newhashset{“ww.stackoverflow.com”};
var contextManager=新的ContentManager(URL);
contextManager.GetHtmlContent();
}

但它返回
内容
而不是异常。在(0)处访问元素抛出异常我正在使用visualStudio单元测试。没有断言。那@EladBenda:这个类是你的,还是某个第三方?你能(你想)换一下吗?在国际海事组织看来,如果这种方法会被抛弃,那就更清楚了。如果你不能改变它的行为,请告诉我。(我已更新测试以匹配MS测试框架)@Elad您可以使用
[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();
}