Reputation: 568
I have a constructor which makes a call to two methods. They are both void, and I just want to verify that they are called.
Foo.java
public class Foo {
public Foo(String name, Object obj) {
init(name);
doSomething(obj);
}
}
FooTest.java
@Test
public void constructor_test throws Exception {
Foo foo = Mockito.mock(Foo.class);
PowerMockito.whenNew(Foo.class).withAnyArguments().thenReturn(foo);
Foo f = new Foo("name");
verify(f).init(Mockito.anyString());
verify(f).doSomething(Mockito.any(Object.class));
}
The unit test fails with a message saying that there were zero interactions with the mock foo.init();.
How do a verify a method call that is within a constructor?
Upvotes: 1
Views: 2097
Reputation: 32936
Can you not test by checking the state of your Foo
?
Ie is there some externally visible getName()
function you could call and verify that the name has been set correctly in the constructor? This is preferable to checking the calling of private methods as then you can refactor the inner working of the class without having to change the tests, as long as the behaviour and external state is the same.
If you find yourself wanting to check that private methods have been called in a unit test then this is a smell and should rethink your approach I think. Some other questions have already covered similar areas.
If these methods are interacting with some external components then you can mock these components as you normally would with any method and then validate the interaction is as you expect. Whether that interaction happens in one method or another internally should be an implementation detail of the Foo
class and externally you shouldn't care.
It feels like your desired approach will result in an extremely brittle test which will need to be changed frequently as the implementation of Foo
changes.
As to your actual question I'm not certain you can do what you want as, according to my understanding, your Foo
is not a 'real' Foo
but a mock Foo
so the real constructor won't be called.
If you are able to it will be by creating a 'PartialMock' and having it delegate to the underlying class. I only have a little experience with Mockito but I think this approach may be possible in some of the other (.NET) mocking frameworks I'm familiar with, though I haven't tried it, but it may give you some extra words to boost your google foo with.
Upvotes: 5