首页 > 解决方案 > 我可以从我正在运行的方法中得到异常错误吗?

问题描述

有没有办法让我在 BeforeAfterTestAttribute 中输入异常?我的目标是在未正确执行时注销 Method 错误并执行其他操作。这或多或少来自这篇文章

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
class ReportBeforeAtribute : BeforeAfterTestAttribute
{
    public override void Before(MethodInfo methodUnderTest)
    {
        Trace.Log("Starting Message");
    }

    public override  void After(MethodInfo methodUnderTest)
    {
        Trace.Log("Method Ended Fine ");
    }

    public void After(MethodInfo methodUnderTest, Exception ex)
    {
        Trace.Log("Exeption " + ex.Message);
    }
}

此处将使用该属性:

  [ReportBefore]
    public class TestClass
    {
        [Theory]
        public async Task CheckMethod()
        {
        //Here Is code which Either runs ok or not
        //If breaks I want to pass the Exception to The Attribute in the 
        // After Method
        }
    }

从上面的代码第一部分和第二部分有效,虽然第三种方法是我想要创建的,但这是行不通的。

有没有办法做到这一点?

标签: c#attributesxunit

解决方案


如果您希望异常不会破坏您的测试,您可能应该期待它。该链接描述了一些如何处理异常。

https://fluentassertions.com/exceptions/


推荐阅读