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.class
that 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
Should I Call Ugi.Checktgtandreloginfromkeytab() Before Every Action on Hadoop
How to Set Request Encoding in Tomcat
Dynamically Change Spring Data Source
How to Get Absolute Path to File in /Resources Folder of Your Project
Java:Parse Java Source Code, Extract Methods
Getting Java.Lang.Classnotfoundexception: Org.Apache.Commons.Logging.Logfactory Exception
CSV Parsing in Java - Working Example
Bigdecimal Equals() Versus Compareto()
How to Format a String in an Email So Outlook Will Print the Line Breaks
Removing Invalid Xml Characters from a String in Java
What Code Folding Plugins Work on Eclipse 3.6
Where Are Compiled Jsp Java (*_Jsp.Java) Files
Why Does Arraylist Have "Implements List"
Mockito: Trying to Spy on Method Is Calling the Original Method