Using Powermockito.Whennew() Is Not Getting Mocked and Original Method Is Called

Using PowerMockito.whenNew() is not getting mocked and original method is called

You need to put the class where the constructor is called into the @PrepareForTest annotation instead of the class which is being constructed - see Mock construction of new objects.

In your case:

@PrepareForTest(MyQueryClass.class)

@PrepareForTest(A.class)

More general:

@PrepareForTest(NewInstanceClass.class)

@PrepareForTest(ClassThatCreatesTheNewInstance.class)

PowerMockito.whenNew() is not getting mocked and original method is called with junit 5

I won't analyze or make any comment about this particular test, but note that up to this point there is no PowerMock support for JUnit 5:

https://github.com/powermock/powermock/issues/830

So you might want to consider using JUnit 4 for this.

PowerMockito.whenNew is not working

You cannot start a test class via main method. Instead it should be run with JUnit. Therefore a @Test annotation has to be present at the test method. Look here for getting started with JUnit.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Class2.class, Class1.class })
public class ClassTest {

@Test
public void runMethod() throws Exception {
Class2 class2 = new Class2();
Class1 class1 = PowerMockito.mock(Class1.class);

PowerMockito.whenNew(Class1.class).withAnyArguments().thenReturn(class1);
PowerMockito.when(class1.mockTestMethod(Mockito.anyString())).thenReturn("MOCKED VALUE");
class2.testingMethod();
}

}

(I left out imports in your testclass)

PowerMockito whenNew thenReturn not working

I researched a little bit, here whenNew does not mock the the methods but the constructor of the class provided (example.class). So if you define a constructor inside example.classthat will be replaced by the constructor of your mock class but example::method() invoked here is the original one.
So now the question is how do we handle this situation, well I found it here take a look.



Related Topics



Leave a reply



Submit