Unable to mock a constructor using PowerMock

17 views Asked by At

I have the following class definitions :

A.java

public final class A {

   public A(){}
   
   public int testB() {
     B newB = new B();
     return newB.getNumber();
   }
}

B.java

public class B {
  public B() {
    throw new Exception("Constructor called");
  }
 
  int getNumber() {
    return 1;
  }
}

My test class looks like this:

@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class})
public class StubTest {
 
 @Test
 public void testMockMethod() throws Exception {
   B mockB = mock(B.class);
   when(mockB.getNumber()).thenReturn(5);
   whenNew(B.class).withNoArguments().thenReturn(mockB);
   A ins = new A();
   assertEquals(ins.testB(), 5);
 }
}

I would expect the constructor of B to not get called and instead using the stub for B, but the constructor ends up getting called and I get the exception message thrown by calling the constructor on B.

Constructor called
java.lang.Exception: Constructor called
0

There are 0 answers