java - powermock whenNew doesnt seem to work, calls the actual constructor

Posted by user1331243 on Stack Overflow See other posts from Stack Overflow or by user1331243
Published on 2012-04-13T11:23:40Z Indexed on 2012/04/13 11:30 UTC
Read the original article Hit count: 274

Filed under:

I have two final classes that are used in my unit test. I am trying to use whenNew on the constructor of a final class, but I see that it calls the actual constructor.

The code is

@PrepareForTest({A.class, B.class, Provider.class})
@Test
public void testGetStatus() throws Exception {
    B b = mock(B.class);
    when(b.getStatus()).thenReturn(1);
    whenNew(B.class).withArguments(anyString()).thenReturn(b);
    Provider p = new Provider();
    int val = p.getStatus();
    assertTrue((val == 1));
}
public class Provider {
    public int getStatus() {
    B b = new B("test");
    return b.getStatus();
    }
}
public final class A {

    private void init() {
    // ...do soemthing
    }

    private static A a;

    private A() {
    }

    public static A getInstance() {
    if (a == null) {
        a = new A();
        a.init();
    }
    return a;
    }
}
public final class B {
    public B() {
    }

    public B(String s) {
    this(A.getInstance(), s);
    }

    public B(A a, String s) {

    }

    public int getStatus() {
    return 0;
    }
}

On debug, I find that its the actual class B instance created and not the mock instance that is returned for new usage and assertion fails. Any pointers on how to get this working. Thanks

© Stack Overflow or respective owner

Related posts about java