PowerMock whenNew without @PrepareForTest?

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 the class A doSomething method with Mockito. So I want to make fun of an instance of class B and pass it to A when it creates an instance of class B. I do not want b.doSomething () to be achieved at all, for isolation reasons.

I know that I can achieve this behavior 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 leads to the conclusion:

doSomething A reached

So this work! However, now my problem is that we are using the Jococo plugin to cover testing. Jococo does not cover code verified using the @PrepareForTest (A.class) statement. And my company appreciates the exact coverage of code testing.

My question is: is there any other way to give A an instance of B without using the @PrepareForTest statement?

Thank you very much in advance!

+4

Source: https://habr.com/ru/post/1528980/


All Articles