在 C# 中混合 MockVerify 和 FluentAssertions.Should()

Mixing MockVerify and FluentAssertions.Should() in C#

我正在单元测试中尝试以下操作:

var sut = new MyClass(dependentOne.Object, dependentTwo.Object);
            Action act = () => sut.DoSomething();
            // Assert
            dependentOne.Verify(m => m.MethodOne(), Times.Once);
            dependentTwo.Verify(m => m.MethodTwo(), Times.Once);
            act.Should().NotThrow<Exception>();

看起来 MethodOne()MethodTwo() 这两个将在 DoSomething() 中调用的方法根本没有被调用,但是如果我不使用 Action 直接调用,就会调用这些方法。

sut.DoSomething();

虽然我没有充实方法和初始化的定义,但上面的代码片段应该足以说明情况。那么,Action act = () => sut.DoSomething(); 不应该实际调用这些方法,以便 Verify 能够按预期工作吗?

该方法只有在

时才会被调用
act()

act.Invoke()

被调用。给一个Action变量赋值相当于一个方法定义,什么都不调用。

但是在您的情况下,它不会抛出的断言将调用该方法,因此如果您将它不会抛出的断言移到 Verify 行之前,一切都应该正常。

您可以在此处查看 NotThrow 的实现方式 https://github.com/fluentassertions/fluentassertions/blob/master/Src/FluentAssertions/Specialized/ActionAssertions.cs