【发布时间】:2022-08-19 23:25:05
【问题描述】:
我有一个类测试,当我运行测试时会向我发送一个错误。 我关注了几个线程,我有正确的 import \"import org.junit.jupiter.api.Test\" 所以我不明白为什么它会向我发送此错误:
无法调用 \"org.springframework.test.web.servlet.MockMvc.perform(org.springframework.test.web.servlet.RequestBuilder)\" 因为 \"this.mockMvc\" 为空
我的代码:
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\")); } }摇篮配置:
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 文件没有这个依赖:
testImplementation \"org.springframework.boot:spring-boot-starter-test:2.7.2\"
-
尝试添加
@AutoConfigureMockMvc类级别注释 -
@Tim 我有同样的错误
标签: java spring spring-boot junit mockito