0

Can anyone give an idea of how to mock object creation for A a= new B() using PowerMockito (Class B implements the interface A)? I have tried as follows. But the mock object is not used in the class under the test but a new object is created under that class.

B b=Mockito.spy(B.class);
PowerMockito.whenNew(B.class).withNoArguments().thenReturn((b));
nihal
  • 124
  • 2
  • Don't, don't, don't, don't, don't. Entire frameworks exist _specifically to prevent you from doing this_. In 98% of cases, pass `b` as a constructor parameter; in the remaining 2%, pass a `Supplier`. – chrylis -cautiouslyoptimistic- Jan 05 '21 at 04:51

1 Answers1

0

You need to do it this way with PowerMockito

B b = PowerMockito.mock(B.class);
PowerMockito.whenNew(B.class).withNoArguments().thenReturn(b);

A working PowerMockito example is given in this answer JUnit: mock a method called inside another method

i.am.jabi
  • 620
  • 1
  • 5
  • 23