【问题标题】:Mixing MockVerify and FluentAssertions.Should() in C#在 C# 中混合 MockVerify 和 FluentAssertions.Should()
【发布时间】:2019-05-11 22:46:14
【问题描述】:

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

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();

虽然我还没有具体说明方法和初始化的定义,但是上面的代码sn-p应该足以说明情况了。那么,Action act = () =&gt; sut.DoSomething(); 不应该实际调用这些方法以使验证按预期工作吗?

【问题讨论】:

    标签: c# .net unit-testing moq fluent-assertions


    【解决方案1】:

    只有在以下情况下才会调用该方法

    act()
    

    或者

    act.Invoke()
    

    被调用。分配一个 Action 变量相当于一个方法定义,并且没有调用任何内容。

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

    你可以在这里看到NotThrow是如何实现的https://github.com/fluentassertions/fluentassertions/blob/master/Src/FluentAssertions/Specialized/ActionAssertions.cs

    【讨论】:

    • 在这种情况下,异常部分是如何工作的? act.Should() 是否真的调用方法然后进行验证?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    相关资源
    最近更新 更多