c# - (MSTest) 扩展 ExpectedExceptionBaseAttribute 隐藏测试失败解释

标签 c# unit-testing exception visual-studio-2012 mstest

运行此测试时:

    [TestMethod]
    [ExpectedException(typeof(SpecialException))]
    public void Test1()
    {
        throw new NotImplementedException();
    }

Visual Studio 告诉我失败的原因:

Test method [...].Test1 threw exception System.NotImplementedException, but exception [...].SpecialException was expected. Exception message: System.NotImplementedException: The method or operation is not implemented.

但是当我尝试扩展 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 生成一条信息量不大的消息:

Exception has been thrown by the target of an invocation.

我在互联网上发现的扩展 ExpectedExceptionBaseAttribute 的所有示例( 123 )都有相同的尝试来提供有关引发异常失败的更多信息,但是没有结果。

我做错了什么吗?有没有办法提供有关此类失败测试的更多信息?

最佳答案

我认为您在问题中引用的任何帖子都没有正确实现自定义 ExpectedException 属性。我并不是说它们不是有效的解决方案,而是说它们解决了不同的问题。我认为您遇到的是一个不同的问题,这些帖子都没有解决该问题。

看来您没有收到完整错误消息的原因是 null TestContext .

您可以通过查看 ExpectedExceptionAttribute 的实现来验证这一点。 您可以使用反射器,您可以看到它内部使用了 TestContext。

如果你看看ExpectedExceptionBaseAttribute的实现

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false,
Inherited = true)]
public abstract class ExpectedExceptionBaseAttribute : Attribute
{
     protected internal TestContext TestContext { get; internal set; }

TestContext 在运行时内部设置,并且不能注入(inject)ExpectedSpecialException 属性中。 MSTest 的ExpectedExceptionAttribute 可以访问由测试运行器内部设置的TestContext。需要注意的是,由于 MSTest 缺乏可扩展性,我们无法真正根据需要访问和设置 TestContext。

不确定这是否有帮助,但您可以自定义异常并使用 this 等方法精确定位抛出异常的位置。 。我认为这是一个更好的方法。

关于c# - (MSTest) 扩展 ExpectedExceptionBaseAttribute 隐藏测试失败解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20284670/

相关文章:

java - 如何为多线程应用程序创建测试环境

java - 使用 @Configuration 运行单元测试时出现 NoSuchBeanDefinitionException

java - Spring boot - @ControllerAdvice 不起作用

php - 在 PHP 中冒泡异常?

c# - IIS 7.5 中的 ASP.NET Core WebAPI 500 内部错误

c# - 带有参数数组的通用 C# 方法重载解析

使用 mqueue.h 和 -lrt 配置 ceedling

单元测试期间的 C# 扩展方法奇怪

c# - 是否可以在回发时伪造查询字符串?

c# - 不能在 ContractClass 中使用 ContractAbbreviator?