You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JUnit 5和Spring Boot时@Autowired注入MockMvc为空问题

MockMvc注入为空的问题解决

运行Spring Boot的Web MVC测试类时,遇到如下错误:

Cannot invoke "org.springframework.test.web.servlet.MockMvc.perform(org.springframework.test.web.servlet.RequestBuilder)" because "this.mockMvc" is null

已正确导入import org.junit.jupiter.api.Test,测试代码如下:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(TestController.class)
public class ControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private CreateMessageProvider createMessageProvider;

    @Test
    public void test() throws Exception {
        this.mockMvc.perform(get("/test"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().string("OK"));
    }
}

对应的Gradle依赖配置:

mockitoCoreVersion = '4.6.1'
        mockitoJunitJupiterVersion = '4.6.1'
        springBootTestVersion = '2.7.2'
        springTestVersion = '5.3.22'

    testImplementation "org.springframework.boot:spring-boot-test:$springBootTestVersion"
    testImplementation "org.springframework:spring-test:$springTestVersion"
    testImplementation "org.mockito:mockito-junit-jupiter:$mockitoJunitJupiterVersion"
    testImplementation "org.mockito:mockito-core:$mockitoCoreVersion"

解决方案:
问题根源在于Gradle依赖中缺少Spring Boot测试启动器,添加以下依赖即可解决:

testImplementation "org.springframework.boot:spring-boot-starter-test:2.7.2"

内容的提问来源于stack exchange,提问作者mtnp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 17:18:08