gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:11:20 25 4
gpt4 key购买 nike

运行此测试时:

    [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)Extending ExpectedExceptionBaseAttribute隐藏测试失败解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20284670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com