I have a private method in my test class that constructs a commonly used Bar
object. The Bar
constructor calls someMethod()
method in my mocked object:
private @Mock Foo mockedObject; // My mocked object
...
private Bar getBar() {
Bar result = new Bar(mockedObject); // this calls mockedObject.someMethod()
}
In some of my test methods I want to check someMethod
was also invoked by that particular test. Something like the following:
@Test
public void someTest() {
Bar bar = getBar();
// do some things
verify(mockedObject).someMethod(); // <--- will fail
}
This fails, because the mocked object had someMethod
invoked twice. I don't want my test methods to care about the side effects of my getBar()
method, so would it be reasonable to reset my mock object at the end of getBar()
?
private Bar getBar() {
Bar result = new Bar(mockedObject); // this calls mockedObject.someMethod()
reset(mockedObject); // <-- is this OK?
}
I ask, because the documentation suggests resetting mock objects is generally indicative of bad tests. However, this feels OK to me.
Alternative
The alternative choice seems to be calling:
verify(mockedObject, times(2)).someMethod();
which in my opinion forces each test to know about the expectations of getBar()
, for no gain.