javaspring-bootjunitjunit5applicationcontext

could not inject application context in Spring Boot Unit test running with @ExtendWith(SpringExtension.class)


I am trying to write Unit tests for a SOAP endpoint written using Spring boot. Initially I wrote tests using @RunWith(SpringJUnit4ClassRunner.class) all the tests were executed successfully. However when I try to upgrade the unit tests using @ExtendWith(SpringExtension.class), tests are failing to run as it could not autowire ApplicationContext object. Below is a part of the old and new code.

Old Code:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfiguration.class})
public class ServiceEndPointTest {
    @Autowired
    private ApplicationContext applicationContext;
    private MockWebServiceClient mockClient;

    @Before
    public void setUp() {
        mockClient = MockWebServiceClient.createClient(applicationContext);
    }

New Code:


@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {TestConfiguration.class})
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@ActiveProfiles(profiles = "unittest")
public class ServiceEndPointTest {
   
    @Autowired
    private ApplicationContext applicationContext;
    private MockWebServiceClient mockClient;

    
    @Before
    public void setUp() {
        mockClient = MockWebServiceClient.createClient(applicationContext);
    }

I am getting below error in setUp() as applicationContext is null.

java.lang.IllegalArgumentException: 'applicationContext' must not be null

    at org.springframework.util.Assert.notNull(Assert.java:198)
    at org.springframework.ws.test.server.MockWebServiceClient.createClient(MockWebServiceClient.java:151)
    at com.test.ServiceEndPointTest.setUp(ServiceEndPointTest.java:80

Not sure what is missing here.

Please help.


Solution

  • Usually errors like this during migration to junit 5 arise from using Junit annotations from the junit 4 packages. The test class you've provided contains the Junit 4-annotation @Before.

    My approach to migrating from Junit 4 to Junit 5 is to delete all imports related to junit 4 before doing anything else, ie. delete all import statements in the org.junit.*-packages.

    Don't keep any of these:

    import org.junit.Before;
    import org.junit.runner.RunWith;
    import org.junit.Test;
    

    Instead, import these (and so on):

    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;
    import org.junit.jupiter.api.extension.ExtendWith;
    

    Deleting the old imports ensures that there are no "forgotten" imports that's still hanging around causing issues with seemingly unrelated error messages like the one you've encountered here.

    Also refer to the Junit 5 user guide, specifically the annotations section