Spring @AutowiredとjUnit 5でMavenテストが失敗しました

Spring @AutowiredおよびjUnit 5でMavenテストが失敗しました

次のjUnit 5の例を確認して、Spring 5 MVC Webアプリケーションをテストしてください。

TestWelcome.java

package com.example.web;

import com.example.web.config.SpringConfig;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@ExtendWith(SpringExtension.class)
@WebAppConfiguration
@ContextConfiguration(classes = SpringConfig.class)
public class TestWelcome {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webAppContext;

    @BeforeEach
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
    }

    @Test
    public void testWelcome() throws Exception {

        this.mockMvc.perform(
                get("/"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(view().name("index"))
                .andExpect(forwardedUrl("/WEB-INF/views/index.jsp"))
                .andExpect(model().attribute("msg", "Hello World"));

    }

    @Test
    public void testAbc() {
        assertEquals(2, 1 + 1);
    }

}

IntelliJ IDEAおよびEclipseで問題なくテストされました。 しかし、Mavenコマンドで失敗しました–mvn test、MavenテストはWebApplicationContextクラスを@Autowiredできないようです。

D:\java-web-project>mvn test

com.example.web.TestWelcome.testWelcome()  Time elapsed: 0.181 sec  <<< FAILURE!
java.lang.NullPointerException
        at com.example.web.TestWelcome.testWelcome(TestWelcome.java:40)


[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.326 s
[INFO] Finished at: 2018-10-05T16:39:18+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test

溶液

上記のコンソールで、Mavenがmaven-surefire-plugin:2.12.4を使用していることに気付きました。これは少し古く、jUnit 5 + Spring5統合をサポートしていない可能性があります。

To fix it、最新の2.22.0に更新

pom.xml

    
        
            
                org.apache.maven.plugins
                maven-surefire-plugin
                2.22.0