Search code examples
junitmockitojunit4junit5powermockito

How do you mix junit5 and junit4 for the sake of PowerMockito?


I'm using junit5, but I am in dire need to mock some static methods and constructors, etc. Since Powermockito only works with Junit4, I need to mix junit4 and junit5. Can someone explain how to do something like that? For example, what would I need to modify in this test case skeleton?

package com.mypackage;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;


@ExtendWith(MockitoExtension.class)
public class MyClass {

    @BeforeEach
    void setup() throws Exception {
        ...
    }

    @Test
    void testRequestHandling() throws Exception {
         ....
    }
}

Solution

  • You can mix JUnit 4 and 5 in a single project, see https://github.com/junit-team/junit5-samples/tree/main/junit5-multiple-engines for how to set that up.

    What you can not do is mix JUnit 4 mechanisms into JUnit 5 (Jupiter) tests. That means that you have to use JUnit 4 tests when using Powermock - since that doesn’t work with Jupiter - but are free to use Jupiter tests for everything else, including plain Mockito.