We Are Going To Discuss About Mock Static Methods in JUnit5 using PowerMockito. So lets Start this Java Article.
Mock Static Methods in JUnit5 using PowerMockito
- Mock Static Methods in JUnit5 using PowerMockito
You're using @Before which is junit4 annotation.. Junit5 have @BeforeEach / @BeforeAll(whichever suits your requirement). Also, your import for @Test are from junit4 but not from junit5(That should be org.junit.jupiter.api.Test;)
- Mock Static Methods in JUnit5 using PowerMockito
You're using @Before which is junit4 annotation.. Junit5 have @BeforeEach / @BeforeAll(whichever suits your requirement). Also, your import for @Test are from junit4 but not from junit5(That should be org.junit.jupiter.api.Test;)
Solution 1
With mockito v 3.4.0 we can simply use mockStatic() method without powermock library :
try (MockedStatic mocked = mockStatic(Foo.class)) {
mocked.when(Foo::method).thenReturn("bar");
assertEquals("bar", Foo.method());
mocked.verify(Foo::method);
}
assertEquals("foo", Foo.method());
Latest documentation and example :
https://javadoc.io/static/org.mockito/mockito-core/3.5.10/org/mockito/Mockito.html#static_mocks
Original Author Of This Content
Solution 2
You’re using @Before which is junit4 annotation.. Junit5 have @BeforeEach / @BeforeAll(whichever suits your requirement). Also, your import for @Test are from junit4 but not from junit5(That should be org.junit.jupiter.api.Test;)
Original Author Of This Content
Solution 3
As your link suggests, still you can’t do power mock stuff with junit-5 directly, simply because there’s no PowerMockRunner
(Extension) still available for junit-5.
However, In your above code possibly what has gone wrong is this line.
when(EnvironmentUtils.isCF()).thenReturn(true);
Here, note that you are using when
of mockito
(by import static org.mockito.Mockito.*;
)
Instead, you have to use the one of PowerMockito
. So
Remove this line import static org.mockito.Mockito.*;
Instead, add this. import static org.powermock.api.mockito.PowerMockito.*;
Original Author Of This Content
Conclusion
So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.