如何使用 Fluent Assertions 来测试不等式测试中的异常?

问题描述 投票:0回答:3

我正在尝试使用 C# 中的 Fluent Assertions 为大于重写运算符编写单元测试。如果任何一个对象为 null,则此类中的大于运算符应该引发异常。

通常在使用 Fluent Assertions 时,我会使用 lambda 表达式将方法放入操作中。然后我将运行该操作并使用

action.ShouldThrow<Exception>
。但是,我不知道如何将运算符放入 lambda 表达式中。

出于一致性考虑,我宁愿不使用 NUnit 的

Assert.Throws()
Throws
约束或
[ExpectedException]
属性。

c# unit-testing lambda nunit fluent-assertions
3个回答
87
投票

你可以尝试这个方法。

[Test]
public void GreaterThan_NullAsRhs_ThrowsException()
{
    var lhs = new ClassWithOverriddenOperator();
    var rhs = (ClassWithOverriddenOperator) null;

    Action comparison = () => { var res = lhs > rhs; };

    comparison.Should().Throw<Exception>();
}

看起来不够整洁。但它有效。

或者分成两行

Func<bool> compare = () => lhs > rhs;
Action act = () => compare();

0
投票

您也可以使用调用

 comparison.Invoking(()=> {var res = lhs > rhs;})
.Should().Throw<Exception>();

更多信息在这里


0
投票

我认为正确的写法应该是这样的:

var value1 = ...;
var value2 = ...;

value1.Invoking(x => x > value2)
.Should().ThrowExactly<MyException>()
.WithMessage(MyException.DefaultMessage);
© www.soinside.com 2019 - 2024. All rights reserved.