Reputation: 798
I have a question regarding one of the feature of mockito. On several blogs I have read that mocking constructor is not possible through mockito.
For one of my test case, currently it is done through powermockito but I want to remove it due to some performance issues.
Currently the code looks something like this:
Actual class:
public class TestClass {
private ClassB classB;
public TestClass(ClassB classB) {
this.classB = classB;
}
}
In my test class, I have code like this:
TestClass testClass = Mockito.mock(TestClass.class);
PowerMockito.whenNew(TestClass.class).withArguments(this.classB)
.thenReturn(testClass);
So could anyone suggest me, is there any other way possible by which I can achieve the same thing through mockito? Also on some blogs, I found that injection a public method with constructor of the class inside and then mocking that method can do the trick. But wanted to know all other options to analyze.
Thanks
-Sam
Upvotes: 0
Views: 295
Reputation: 789
I am not sure if that can help you.
class MyClass {
private final MySecondClass clazz;
MyClass(MySecondClass clazz) {
this.clazz = clazz;
}
public boolean executeDoSomething() {
return clazz.doSomething();
}
}
And in the test you could mock the inner class:
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@Test
public void MyClassTest() {
MySecondClass mockedPerformer = Mockito.mock(MySecondClass.class);
MyClass clazz = new MyClass(mockedPerformer);
clazz.executeDoSomething();
}
}
I hope this helps you.
Upvotes: 2