spring 无法自动连接,找不到'MockMvc'类型的Bean-是否已正确导入、正确配置并且在其他项目中工作正常?

mwkjh3gx  于 2022-10-30  发布在  Spring
关注(0)|答案(1)|浏览(630)

在我的控制器测试类中,我尝试使用Mockito和MockMVC来独立测试控制器层。我重用了以前项目中的代码,但由于某种原因,它在这个新项目中不起作用,尽管包含相同的配置、导入等。

import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
    import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
    import org.springframework.boot.test.mock.mockito.MockBean;
    import org.springframework.http.MediaType;
    import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@AutoConfigureMockMvc
@WebMvcTest(controllers = UserController.class)
public class UserControllerTests {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @MockBean
    private UserRepository userRepository;

    @Test
    public void FindPlayersSuccessfully() throws Exception {

        String json = "{\"userID\":\"1\"}";

        mockMvc.perform(post("/api/v1/users/find-users")
                .contentType(MediaType.APPLICATION_JSON)
                .content(json).characterEncoding("utf-8"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.response").value("Success"));
    }

IDEA以红色突出显示了“MockMvc mockMvc”自动连接,当我将鼠标悬停在错误上时,它显示“无法自动连接。未找到”MockMvc“类型的bean”
另外,我注意到的一件可能很奇怪的事情是,当我一个接一个地添加导入时,MockMvc导入确实起作用了,突出显示消失了,但是当我添加:

import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;

导入时,出现问题。
谢谢你的帮助!

gmol1639

gmol16391#

我也遇到了同样的问题。在Intelij Idea File-〉Settings-〉Editor-〉CodeStyle-〉Inspections中尝试,然后选择Spring Core -〉Code,并将“Spring Bean组件中的错误注入点自动配置”的严重性从Error更改为Warning。

相关问题