When building a unit test, is it appropriate to use a mocking tool to assist you in setting up an object even if you will not be mocking any behavior or verifying any interaction with that object?
Here is a simple example in pseudo-code:
//an object we actually want to mock
Object someMockedObject = new Mock(Object.class);
EqualityChecker checker = new EqualityChecker(someMockedObject);
//an object we are stubbing/mocking only to avoid figuring out how to instantiate or
//tying ourselves to some constructor that may be removed in the future
ComplicatedObject someObjectThatIsHardToInstantiate = new Mock(ComplicatedObject.class);
//set the expectation on the mock
When(someMockedObject).equals(someObjectThatIsHardToInstantiate).return(false);
Assert(equalityChecker.check(someObjectThatIsHardToInstantiate)).isFalse();
//verify that the mock was interacted with properly
Verify(someMockedObject).equals(someObjectThatIsHardToInstantiate).oneTime();
Is it appropriate to mock ComplicatedObject in this scenario?
2
You don’t really want a mock object. You want a stub. Basically you want a dumb object that takes the place of something complex so you can control that complex process without needing to validate that it works.
Mocks Aren’t Stubs (Martin Fowler)
4
With Mockito, I would use the any()
matcher.
When(someMockedObject).equals(any(ComplicatedObject.class)).return(false);
There might be something similar in your mocking framework.
1
If “you will not be mocking any behavior or verifying any interaction with that object”, it sounds like you will not be using that object at all in the unit under test, for that test. Can you just set the reference to null for that test? This makes it very clear that this dependency is irrelevant in this test.
If that is not possible, and you require it to be non-null, it means in fact you are expecting some interaction with it. If your use case really shouldnt be interacting with it at all, it kind of seems like the code under test has a design issue.
1