intellij 无法自动装配。未找到“MockMvc”类型的 bean。但测试没问题

问题描述 投票:0回答:2

我想知道我能看到这个错误(无法自动装配。找不到“MockMvc”类型的 bean。)

这是我的代码

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.test.web.servlet.MockMvc;

import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;


@WebMvcTest(HomeController.class)
public class HomeControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testHomePage() throws Exception {
        mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(view().name("home"))
                .andExpect(content().string(
                        containsString("Welcome to...")));
    }
}

此测试代码运行成功。但mockMVC显示有关自动拧紧的错误。

如何删除这个错误?

请任何人帮忙。

我正在使用 IntelliJ IDEA 2022.1.1(终极版)、java、spring、junit5。

谢谢

intellij-idea junit5
2个回答
7
投票

我在 2021.3.1(终极版)版本中遇到了相同的编辑器错误。您可以忽略添加 @SuppressWarnings 标签的特定错误点:

@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Autowired
private MockMvc mockMvc;

这也可以在编辑器的帮助下生成: 右键单击变量 > 显示上下文操作 > 检查“Spring bean 组件中不正确的注入点自动装配”选项 > 抑制字段

另一种方法是更新编辑器。目前我使用的是2022.2.2,未检测到错误。


0
投票

要在测试类中使用 MockMvc,您应该添加 @AutoConfigureMockMvc 注释和 @SpringBootTest。此注释告诉 Spring 为您的测试自动配置 MockMvc 实例。这是更正的示例:

import org.junit.jupiter.api.Test
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.web.servlet.MockMvc

@SpringBootTest
@AutoConfigureMockMvc
class YourApplicationTest {

    @Autowired
    private lateinit var mockMvc: MockMvc

    @Test
    fun contextLoads() {
        // Check if the ApplicationContext has been loaded successfully
        assertNotNull(mockMvc, "MockMvc bean should be initialized")
        
        // You can add more assertions as needed
        // For example, assert that specific controllers have been created
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.