spring - 无法在 Spring Boot 测试 1.4 中找到 SpringBootConfiguration

标签 spring spring-mvc testing spring-boot spring-test

我无法在 spring boot 1.4 中运行简单测试。我遵循了官方网站上的教程 testing-the-spring-mvc-slice但我没有让它工作。

每次我收到以下错误:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

有什么想法、提示吗?

提前致谢

编辑:

这是 Controller

@Controller
public class UserManagementController {

@GetMapping(value = "/gs/users/getUsers")
    public @ResponseBody String getAllUsers() {
        return "test";
    }
}

这是测试

@RunWith(SpringRunner.class)
@WebMvcTest(UserManagementController.class)
public class UserManagementControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void showUserView() throws Exception {
        this.mvc.perform(get("/gs/users/getUsers"))
            .andExpect(status().isOk())
            .andDo(print());
    }
}

从我的角度来看,它与网站上的这篇帖子完全一样。

@WebMvcTest 会做:

  • 自动配置 Spring MVC、Jackson、Gson、消息转换器等。
  • 加载相关组件(@Controller@RestController@JsonComponent等)
  • 配置模拟MVC

现在为什么我需要配置一个“ super ”类

最佳答案

The search algorithm works up from the package that contains the test until it finds a @SpringBootApplication or @SpringBootConfiguration annotated class. As long as you’ve structure your code in a sensible way your main configuration is usually found.

因此,您已经使用 @*Test 注释了您的测试。它运行,检查子类中的配置,没有找到,抛出异常。

你必须在测试类的包或子包中有一个配置,或者直接将配置类传递给 @ContextConfiguration@SpringBootTest 或者用 注释类@SpringBootApplication.

根据@SpringBootApplication。我已经按照您在 @WebMvcTest 中提到的方式测试了 Controller :如果应用程序具有注释为 @SpringBootApplication 的类,它就会工作,如果没有,则会失败,您提到的异常。你提到的文章有备注:

In this example, we’ve omitted classes which means that the test will first attempt to load @Configuration from any inner-classes, and if that fails, it will search for your primary @SpringBootApplication class.

Github discussion大致相同点。

Spring Boot Documentation

关于spring - 无法在 Spring Boot 测试 1.4 中找到 SpringBootConfiguration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40215606/

相关文章:

java - 如何使用Spring Batch实现步骤的分布式处理

java - 使用 spring 3 以用户可以更改的频率运行作业/异步任务

json - Spring MVC @Scope 代理 bean 和 Jackson 2

没有 Spring Boot 的 Spring Security JWT 示例

java - 验证模拟对象中的对象被传递到 Mockito 中的参数

html - IE7 按钮样式不正确,CSS 样式错误?

java - Spring-MVC、Hibernate、Postgres : Searching in database with multiple variables

java - Spring MVC : Not able to connect to Rest service

java - 使用 rest 调用更新 xml 文件路径

xcode - 测试 mac 通用二进制文件