Let's say I have this function:
fun method() {
val obj = Obj()
obj.callsMethod()
obj.callsOtherMethod()
}
How can I do something similar to verify(obj).callsMethod()? Is there any other way I could test this method?
CodePudding user response:
You have three alternatives:
- Using the injection
- Using PowerMockito
- Refactor the code in a test friendly manner
Using the injection
If the object Obj is injected in your class under test, instead of has been initialized in the method, you will be able to inject a mock and then use the expression
verify(obj).callsMethod()
that you already knew and that is right.
Using PowerMockito
With powermockito you can write something like this
@RunWith(PowerMockRunner.class)
@PrepareForTest({Obj.class})
class MyJunit{
....
@Test
public void test() throws Exception{
Obj myMock = Mockito.mock(Obj.class);
PowerMockito.whenNew(Obj.class).withAnyArguments().thenReturn(myMock);
// here your test
}
At this point you can use the expression you already knew and that is right.
Refactor
You can use a protected
method in order to build th Obj
and mock this method in your junit in order to return a mock version of the Obj and then use the expression you already knew and that is right.