Search code examples
c#.netunit-testingmoqfluent-assertions

Mixing MockVerify and FluentAssertions.Should() in C#


I am trying the following in my Unit Test:

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

Looks like the two methods of MethodOne() and MethodTwo() that will get called within DoSomething() are not called at all, but if I directly call without Action, the methods are called.

sut.DoSomething();

Although I haven't fleshed out the definition for the methods and initialization, but the above code snippet should be enough to explain the situation. So, shouldn't Action act = () => sut.DoSomething(); actually call the methods so Verify will work as expected?


Solution

  • The method will only be called if

    act()
    

    Or

    act.Invoke()
    

    Is called. Assigning an Action variable is equivalent to a method definition and nothing is invoked.

    However in your case the assertion that it does not throw will invoke the method so if you move your assertion that it doesn't throw before the Verify lines everything should work fine.

    You can see how NotThrow is implemented here https://github.com/fluentassertions/fluentassertions/blob/master/Src/FluentAssertions/Specialized/ActionAssertions.cs