如果在 C#/XUnit 中抛出特定异常,如何提供自定义错误消息?
How to provide a custom error message if a specific exception is thrown in C#/XUnit?
我目前有一个集成测试,我在其中执行一些操作,例如:
var link = await Blah();
偶尔,Blah()
会抛出异常。我想记录异常,如果它匹配某种类型,我想通知用户一个常见的潜在修复。
我目前的做法是 try/catch,但我不确定:
XUnit 向用户推荐的输出方法是什么?我猜 Console.WriteLine
在这里不好吗?
有没有比 try/catch 更简洁的方法?我仍然需要 link
值。
Xunit 删除了 Assert.DoesNotThrow
断言方法,这在这种情况下是合适的。
您可以结合使用 Record.Exception
和 Assert.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 将在输出结果中显示它的消息,其他开发人员在生产或调试期间看到此类异常时也会看到潜在的修复。
听起来您的测试结构有效。为了将信息写入测试输出,您需要使用 ITestOutputHelper
接口。如果你的测试构造函数有一个 ITestOutputHelper
类型的参数,XUnit 将注入它。有关详细信息,请参阅 the XUnit docs。
我目前有一个集成测试,我在其中执行一些操作,例如:
var link = await Blah();
偶尔,Blah()
会抛出异常。我想记录异常,如果它匹配某种类型,我想通知用户一个常见的潜在修复。
我目前的做法是 try/catch,但我不确定:
XUnit 向用户推荐的输出方法是什么?我猜
Console.WriteLine
在这里不好吗?有没有比 try/catch 更简洁的方法?我仍然需要
link
值。
Xunit 删除了 Assert.DoesNotThrow
断言方法,这在这种情况下是合适的。
您可以结合使用 Record.Exception
和 Assert.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 将在输出结果中显示它的消息,其他开发人员在生产或调试期间看到此类异常时也会看到潜在的修复。
听起来您的测试结构有效。为了将信息写入测试输出,您需要使用 ITestOutputHelper
接口。如果你的测试构造函数有一个 ITestOutputHelper
类型的参数,XUnit 将注入它。有关详细信息,请参阅 the XUnit docs。