I am writing Junit jupiter test for project. I am trying to mock new instance creation using mock. but instead of getting mock object i am getting actual object
please see my code below
Main java class
public class TestSubjectClass {
public String doSomething() {
Integer number = new Integer(1);
return internalLogic(number.toString());
}
}
My test class
@RunWith(PowerMockRunner.class)
@PrepareForTest(TestSubjectClass.class)
class TestSubjectClassTest {
@Test
public void mockNewObjectCreation() throws Exception {
TestSubjectClass testedClass = new TestSubjectClass();
Integer mockedValue = new Integer(5);
PowerMockito.whenNew(Integer.class).withAnyArguments().thenReturn(mockedValue);
String output = testedClass.doSomething();
assertThat(output, CoreMatchers.containsString("Here is an input: 5"));
}
}
My pom.xml
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
When i run junit 5 test the actual mocking of new instance is not happening . Any clue what i did wrong
Java.lang.assertionerror: Expected: a string containing "Here is an input 5" but was "Here is an input 1"
Error:
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.