Moq: how do I claim that the methods of my fraudulent object are NOT running?

I have works in which I test that the methods on my mocked object are called with the correct parameters and return the correct result.

Now I want to check another condition. In this case, NO methods must be performed on the mocked object. How can I express this in unit test?

+6
unit-testing moq
source share
2 answers

You could create your layout as rigorous. Thus, only those methods that you install are allowed (or Expect, depending on which version of Moq you are playing with).

var foo = new Mock<IFoo>(MockBehavior.Strict); foo.Expect(f => f.Bar()); 

Any time a method is called in foo other than Bar (), an exception will be thrown and your test will fail.

+16
source share

The two easiest ways are to use MockBehaviour.Strict:

 var moqFoo = new Mock<IFoo>(MockBehaviour.Strict); //any calls to methods that there aren't expectations set for will cause exceptions 

or you can always use a callback and throw an exception from it (if there is a special method that should not be called.

 var moqFoo = new Mock<IFoo>(MockBehaviour.Loose); moqFoo.Expect(f => f.Bar()).Callback(throw new ThisShouldNotBeCalledException()); 
+3
source share

All Articles