I have one class.
Class First {
private Second second;
public First(int num, String str) {
second = new Second(str);
this.num = num;
}
... // some other methods
}
I want to write unit tests for public methods of class First. I want to avoid execution of constructor of class Second.
I did this:
Second second = Mockito.mock(Second.class);
Mockito.when(new Second(any(String.class))).thenReturn(null);
First first = new First(null, null);
It is still calling constructor of class Second. How can i avoid it?
Once again the problem with unit-testing comes from manually creating objects using
newoperator. Consider passing already createdSecondinstead:I know this might mean major rewrite of your API, but there is no other way. Also this class doesn’t have any sense:
First of all Mockito can only mock methods, not constructors. Secondly, even if you could mock constructor, you are mocking constructor of just created object and never really doing anything with that object.