【发布时间】:2013-11-29 11:25:32
【问题描述】:
运行此测试时:
[TestMethod]
[ExpectedException(typeof(SpecialException))]
public void Test1()
{
throw new NotImplementedException();
}
Visual Studio 告诉我失败的原因:
测试方法 [...].Test1 抛出 异常 System.NotImplementedException,但异常 [...].SpecialException 是预期的。例外 消息:System.NotImplementedException:方法或操作是 未实施。
但是当我尝试像这样扩展ExpectedExceptionBaseAttribute(期望SpecialException中的错误代码)时:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
class ExpectedSpecialException : ExpectedExceptionBaseAttribute
{
protected override void Verify(Exception exception)
{
SpecialException se = exception as SpecialException;
if (se == null)
{
RethrowIfAssertException(exception);
throw new Exception("SpecialException was expected but test method threw another one");
}
}
}
并像这样使用它:
[TestMethod]
[ExpectedSpecialException]
public void Test1()
{
throw new NotImplementedException();
}
VS 产生了一条信息量不大的消息:
调用的目标已抛出异常。
我在互联网上找到的所有扩展ExpectedExceptionBaseAttribute 的示例(1,2,3)都有相同的尝试来提供有关抛出异常中失败的更多信息,但没有结果。
我做错了吗?有没有办法提供有关此类失败测试的更多信息?
【问题讨论】:
-
该异常是由您的 Verify 方法触发的,您应该看到 InnerException 与您抛出的异常匹配。不是 MSDN 告诉你的方式,你应该使用 Assert()。
标签: c# unit-testing exception visual-studio-2012 mstest