3
votes

I have a database manipulating object as a dependency of my UUT (Unit Under Test). Therefore, I want to make it as a strict mock, because I also want to make sure that the UUT does not call any other methods that can result db change.

In rhino mocks I did the following:

  1. I made a strictmock from the db object
  2. I made an .Expect clause in Arrange
  3. I called VerifyAllExpectations in Assert

However, when I want to do this in FakeItEasy, I can't find how to do it without code duplication. I tried putting the CallsTo()+MustHaveHappened() parts in the Arrange, but then my test fail. If I put the CallsTo()+MustHaveHappened() parts in the Assert, then my test fail also, because unexpected calls were made to a strict fake. Can this be done without putting the CallsTo call into both Arrange and Assert?

2
UUT = Unit Under Test?Adam Ralph
Yes, UUT = Unit Under TestKornél Regius
I see, thanks. I hadn't heard that term before. I usually use SUT - System Under Test.Adam Ralph

2 Answers

6
votes

Whilst the answer from @jimmy_keen will work (I even upvoted it) a more idiomatic use of FakeItEasy would be:

// Arrange
var service = A.Fake<IService>(o => o.Strict()); // only allows configured calls
A.CallTo(() => service.PostData("data")).DoesNothing(); // allow a specific call

// Act
testedObject.CallService("data");

// Assert
A.CallTo(() => service.PostData("data")).MustHaveHappened(Repeated.Exactly.Once);

--- UPDATE ---

With help from @blairconrad over at https://github.com/FakeItEasy/FakeItEasy/issues/198#issuecomment-29145440 I think this is the neatest way to do this, without duplication:

// Arrange
var service = A.Fake<IService>(o => o.Strict()); // only allows configured calls
var expectedCall = A.CallTo(() => service.PostData("data"));
expectedCall.DoesNothing(); // allow the call

// Act
testedObject.CallService("data");

// Assert
expectedCall.MustHaveHappened(Repeated.Exactly.Once);
5
votes

You can achieve that with following verifications:

var service = A.Fake<IService>();

testedObject.CallService("data");

// verify your specific call to .PostData
A.CallTo(() => service.PostData("data")).MustHaveHappened(Repeated.Exactly.Once);
// verify that no more than 1 call was made to fake object
A.CallTo(service).MustHaveHappened(Repeated.Exactly.Once); 

The A.CallTo(object) overload allows you to make a generic setup/verification on all and any of the fake object methods.