C#单元测试预期异常
我为基于ExpectedExceptionBaseAttribute的单元测试创建了一个自定义属性:C#单元测试预期异常,c#,mstest,C#,Mstest,我为基于ExpectedExceptionBaseAttribute的单元测试创建了一个自定义属性: public class ExpectedEngineExceptionAttribute : ExpectedExceptionBaseAttribute 我覆盖验证方法,如下所示: protected override void Verify(Exception exception) { RethrowIfAssertException(exception)
public class ExpectedEngineExceptionAttribute : ExpectedExceptionBaseAttribute
我覆盖验证方法,如下所示:
protected override void Verify(Exception exception)
{
RethrowIfAssertException(exception);
throw new Exception("Hola!!");
}
下面是TestMethod(它调用一个抛出
单元测试窗口中的输出仅显示:
Exception has been thrown by the target of an invocation.
我只想看到留言Hola
当我运行以下测试方法时:
[TestMethod]
[ExpectedException(typeof(EngineException))]
public void MyTest2()
{
SomeCode();
}
输出为:
测试方法NotificationInputAttributeInvalidTypeTest引发异常System.exception,但应为异常EngineeException。异常消息:系统。异常:SS
在输出窗口中显示“Hola”异常消息时,我遗漏了什么
我反编译了ExpectedExceptionAttribute,并执行了它在自定义属性中所做的操作,但它不起作用
更新:添加断点确认抛出异常(“Hola!!”):
当 “如果异常是AssertFailedException或AssertnConclusiveException,则再次引发异常” 所以,如果这是抛出一个异常,它将永远不会到达您的“Hola”异常抛出
它在VS 2013更新2中运行良好: 守则:
[TestClass]
public class MyTests
{
[TestMethod]
[ExpectedEngineExceptionAttribute]
public void MyTest()
{
throw new Exception("HI");
}
}
public class ExpectedEngineExceptionAttribute : ExpectedExceptionBaseAttribute
{
protected override void Verify(Exception exception)
{
RethrowIfAssertException(exception);
throw new Exception("Hola!!!");
}
}
我建议不要使用属性来定义测试断言。尝试遵循“AAA”风格,并在C#代码中明确声明。这也会使调试变得更容易。另请参见:感谢您的建议,但我需要使用一个属性。您使用的是.net和visual studio的哪个版本?你的代码适合我,我得到了
Hola代码>我做了与ExpectedException完全相同的事情。此外,删除RethrowIfAssertException不会改变任何内容。它仍然显示调用的目标已抛出异常。您是否在其中放置断点以查看它是否会抛出您的“Hola”异常?是的,我已设置。我更新了我的问题并添加了一个屏幕截图。您是否查看了异常,以查看是否捕获、重写和抛出了Hola异常,或者查看堆栈跟踪,看看是否有其他东西在这之后抛出异常?我将使用Console.WriteLine来编写有关测试失败原因的信息。。又是一个变通办法。。谢谢
[TestClass]
public class MyTests
{
[TestMethod]
[ExpectedEngineExceptionAttribute]
public void MyTest()
{
throw new Exception("HI");
}
}
public class ExpectedEngineExceptionAttribute : ExpectedExceptionBaseAttribute
{
protected override void Verify(Exception exception)
{
RethrowIfAssertException(exception);
throw new Exception("Hola!!!");
}
}