views:

448

answers:

2

I have mocks working where I test that methods on my mocked object are called with the correct parameters, and return the right result.

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

+2  A: 

The two most straightforward way would be 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 could always use a callback and throw an exception from there (if there is a specific method that should not be called.

var moqFoo = new Mock<IFoo>(MockBehaviour.Loose);  
moqFoo.Expect(f => f.Bar()).Callback(throw new ThisShouldNotBeCalledException());
Hamish Smith
@Hamish Smith: Your two comments are identical. Is it your intention?
Nam Gi VU
@Nam Gi VU, no, have removed second occurrence. Thanks for that.
Hamish Smith
+8  A: 

You could create your mock as strict. That way only the methods you Setup (or Expect, depending on which version of Moq you're playing with) are allowed to be run.

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

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

Matt Hamilton
Thanks! I wasn't sure what to look for in the documentation (as little as there is).
David White