PowerMock whenNew without @PrepareForTest?
-
21-12-2019 - |
Question
This is my situation, I have 2 very simple classes:
public class B {
public void doSomething(){
System.out.println("doSomething B reached");
}
}
And:
public class A {
public void doSomething(){
B b = new B();
b.doSomething();
System.out.println("doSomething A reached");
}
}
I want to test method doSomething of class A with Mockito. Therefor, I want to mock an instance of class B and give this to A when it is instantiating class B. I don't want b.doSomething() to be reached at all, for isolation reasons.
I know I can reach this behaviour by creating the following unittest:
@RunWith(PowerMockRunner.class)
public class TestA {
@Test
@PrepareForTest(A.class)
public void testDoSomethingOfA() throws Exception{
A a = PowerMockito.spy(new A());
B b = PowerMockito.mock(B.class);
PowerMockito.whenNew(B.class).withNoArguments().thenReturn(b);
a.doSomething();
}
}
which results in output:
doSomething A reached
So this work! However, my problem now is that we use the Jococo plugin for test coverage. Jococo doesn't cover code tested with the @PrepareForTest(A.class) statement. And my company values accurate code testing coverage.
My question: Is there another way around to give A an instantiation of B without having to use the @PrepareForTest statement?
Many thanks in advance!
Solution
To answer my own question, yes, use an agent: https://github.com/jayway/powermock/wiki/PowerMockAgent
OTHER TIPS
@Rens Groenveld: After integrating PowerMockAgent, did you make any changes in your test class or source code ? I tried integrating PowerMockAgent and removed my main source class from @PrepareForTest but the behavior is same (creating new instance instead of mock).
I have tried jacoco offline instruments and many other solution, It did not work.
I can not post to your comment (needs 50 points) hence added as answer.