Using FakeItEasy, how do I check to see if my object's method calls another method on this same object?
The Test:
[TestMethod]
public void EatBanana_CallsWillEat()
{
var banana = new Banana();
var myMonkey = new Monkey();
myMonkey.EatBanana(banana);
//this throws an ArgumentException, because myMonkey is a real instance, not a fake
A.CallTo(() => myMonkey.WillEat(banana)
.MustHaveHappened();
}
The Class:
public class MyMonkey {
private readonly IMonkeyRepo _monkeyRepo;
public MyMonkey(IMonkeyRepo monkeyRepo) {
_monkeyRepo = monkeyRepo;
}
public void EatBanana(Banana banana) {
//make sure the monkey will eat the banana
if (!this.WillEat(banana)) {
return;
}
//do things here
}
public bool WillEat(Banana banana) {
return !banana.IsRotten;
}
}
I'm open to suggestions. If I'm going about this all wrong, please let me know.
WillEat
lived on another object, we'd all be urging the faking of that object and injecting it intoMyMonkey
(sounds painful). All I can really say is that I think the best default position would be to try to testMyMonkey
from the outside, relying on a client's observable results. But, you've put thought into it, and have found a solution that will save you pain and reduces the number of tests as well as the number that will break for a given. You know the code best, so if it works for you… I just wanted you to be aware of the alternative. – Maronite