4

I have a sample test class where I want to mock a static class.My build.gradle is like

testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.2.0'
testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: '5.2.0'
testRuntime group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.2.0'
testRuntime("org.junit.platform:junit-platform-launcher:1.1.1")

testCompile group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.0-beta.5'
testCompile group: 'org.mockito', name: 'mockito-core', version: '2.21.0'
testCompile group: 'org.mockito', name: 'mockito-junit-jupiter', version: '2.21.0'`

When I try my test case as

@ExtendWith(MockitoExtension.class)
@PrepareForTest(MyUtil.class)
public class MyTest {

@Test
public void shouldCheckIfSyncTimeIsAboveThreshold() {
    mockStatic(MyUtil.class);
    when(MyUtil.getValue()).thenReturn(5));
 }

But when I run this, I got exception like

org.powermock.api.mockito.ClassNotPreparedException:
The class MyUtil not prepared for test

Is there any way that I can achieve the same

Sam Brannen
  • 29,611
  • 5
  • 104
  • 136
Priya
  • 1,096
  • 4
  • 15
  • 32
  • Possible duplicate of [PowerMockito ClassNotPreparedException](https://stackoverflow.com/questions/46624589/powermockito-classnotpreparedexception) – mkasberg Aug 10 '18 at 14:08
  • @Ciaran Whyte Do you mean something like this? [Mock Static Methods in JUnit5 using PowerMockito](https://stackoverflow.com/questions/61975300/mock-static-methods-in-junit5-using-powermockito) – vnavs Oct 21 '20 at 18:58

1 Answers1

7

The MockitoExtension does not support Powermock.

Thus, there is no extension registered that would handle @PrepareForTest(MyUtil.class).

For details on how to use Powermock, visit the project webpage.

Sam Brannen
  • 29,611
  • 5
  • 104
  • 136
  • 4
    I have not seen one thing in this documentation that shows how to integrate with JUnit 5. – Ciaran Whyte Aug 07 '20 at 15:46
  • 1
    For JUnit 5 you can use Mockito with version greater than 3.4.0, no need to use PowerMock, Follow this article, https://www.baeldung.com/mockito-mock-static-methods. I followed this article for mocking Final class and static method and It worked like a charm !! – Jay Yadav Dec 13 '22 at 10:24