Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot JUnit 5 test with @ExtendWith(MockitoExtension.class) not working - mocks are null, MockitoJUnitRunner is working

I just migrated my project from Spring Boot 2.1 to 2.3 and thus have now JUnit 5 (with vintage) in place (also including mockito-core and mockito-junit-jupiter of version 3.3.3). While all JUnit 4 tests are working fine my first JUnit 5 tests is not working correctly:

@ExtendWith(MockitoExtension.class)
public class SomeTest {

    @InjectMocks
    private Some to;

    @Mock
    private SomeProperties properties;

    @Test
    public void applied() {
         ....
         //properties is null -> NPE
         when(properties.getSome()).thenReturn("some");
         ....
    }

The mocks are not injected (NPE in when statement). If i switch to old JUnit 4 style @RunWith(MockitoJUnitRunner.class) all is working fine.

So probably the old runner or vintage runner is used?

How to fix this and get tests with "@ExtendWith" working? I thought i can migrate step by step - let new tests run with junit5 runner.

like image 206
dermoritz Avatar asked Jun 08 '20 12:06

dermoritz


People also ask

What is the use of @ExtendWith Mockitoextension class?

The @ExtendWith annotation is used to load a JUnit 5 extension. JUnit defines an extension API, which allows a third-party vendor like Mockito to hook into the lifecycle of running test classes and add additional functionality.

Does JUnit 5 work with Mockito?

Mockito provides an implementation for JUnit5 extensions in the library — mockito-junit-jupiter.

Does JUnit 5 support Powermock?

Power mock is not compatible with JUnit5 So we will discuss it will JUnit4.


1 Answers

Ensure you use the correct import for the @Test annotation:

  • JUnit 4: org.junit.Test

  • JUnit 5: org.junit.jupiter.api.Test

like image 126
Wim Deblauwe Avatar answered Oct 05 '22 22:10

Wim Deblauwe