【问题标题】:How to provide a custom error message if a specific exception is thrown in C#/XUnit?如果在 C#/XUnit 中引发特定异常,如何提供自定义错误消息?
【发布时间】:2020-05-19 16:15:03
【问题描述】:

我目前有一个集成测试,我在其中执行一些操作,比如:

var link = await Blah();

偶尔,Blah() 会抛出异常。我想记录异常,如果它匹配某种类型,我想通知用户一个常见的潜在修复。

我目前的方法是尝试/捕获,但我不确定:

  1. XUnit 推荐的输出给用户的方法是什么?我猜Console.WriteLine这里不好?

  2. 有没有比 try/catch 更简洁的方法?我仍然需要link 值。

【问题讨论】:

    标签: c# testing integration-testing xunit


    【解决方案1】:

    Xunit 删除了Assert.DoesNotThrow 断言方法,这在这种情况下是合适的。
    您可以结合使用Record.ExceptionAssert.False 方法。

    Assert.False,因为Assert.IsNotType<T> 方法没有自定义断言消息的重载

    var exception = Record.ExceptionAsync(() => Blah());
    
    Assert.False(exception is CertainTypeException, "Shouldn't throw, can fix it with ...");
    

    使用 FluentAssertion 库,您可以按照以下方式进行操作

    Func<Task> callBlah = () => Blah();
    
    await callBlah.Should().NotThrowAsync("Shouldn't throw, can fix it with ...");
    

    替代选项,在您的情况下,我更喜欢以前的选项,将潜在修复信息添加到异常消息中。

    public class MyCertainException : Exception
    {
        public MyCertainException (string message) : base($"{message}. Can be fixed with...")
        {
    
        }
    }
    

    使用最后一种方法你什么都不用做,如果抛出异常,Xunit 将在输出结果中显示它的消息,其他开发人员在生产或调试过程中看到此类异常时也会看到潜在的修复。

    【讨论】:

      【解决方案2】:

      听起来您的测试结构有效。为了将信息写入测试输出,您需要使用ITestOutputHelper 接口。如果您的测试的构造函数具有ITestOutputHelper 类型的参数,XUnit 将注入它。详情请见the XUnit docs

      【讨论】:

        猜你喜欢
        • 2015-05-05
        • 1970-01-01
        • 1970-01-01
        • 2014-11-26
        • 1970-01-01
        • 2022-11-25
        • 1970-01-01
        • 2011-08-31
        • 2018-12-09
        相关资源
        最近更新 更多