gpt4 book ai didi

spring-boot - 仅使用一个 Bean 的 Spring 上下文测试

转载 作者:行者123 更新时间:2023-12-03 16:08:33 32 4
gpt4 key购买 nike

在上下文中仅配置一个被测主题的情况下,运行 Spring Boot 测试的推荐方法是什么。

如果我用

@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.profiles.active=test")
@ContextConfiguration(classes = MyTestBean.class)

然后它似乎工作 - 测试通过,上下文快速启动并且似乎只包含我想要的 bean。然而,这似乎是对 @ContextConfiguration(classes = MyTestBean.class) 的错误使用。注解。如果我理解正确,我引用的类应该是 Configuration例如,类,而不是常规的 Spring 服务 bean 或组件。

是对的吗?或者这确实是实现这一目标的有效方法?我知道还有更复杂的例子,比如 org.springframework.boot.test.autoconfigure.json.JsonTest哪个使用 @TypeExcludeFilters(JsonExcludeFilter.class)控制上下文 - 但这对我的用例来说似乎有点过分了。我只想要我的一个 bean 的上下文。

澄清

我知道我可以在没有 Spring 上下文测试的情况下将我正在测试的一个 bean 构建为 POJO,并删除上面的三个注释。但在我的精确用例中,我实际上依赖于通过 application-test.properties 中的设置应用于上下文的一些配置。文件 - 这就是为什么我使用配置文件集进行 Spring Boot 测试的原因。从我的角度来看,这不是独立于 spring 上下文配置的单个类的简单单元测试——测试依赖于正在应用的某些配置(当前由 spring boot 应用程序属性提供)。我确实可以通过在 spring 上下文之外创建一个新实例来将组件测试为 POJO,我正在使用构造函数注入(inject)使提供必要的依赖项变得简单,但是测试确实依赖于日志级别之类的东西(测试实际上使某些正在生成的日志的断言),这需要正确设置日志级别(目前正在通过 logging.level.com.example=DEBUG 在设置 spring 上下文的属性文件中完成)。

最佳答案

对于初学者,首先阅读文档(例如,此答案中链接的 JavaDoc)是推荐的最佳实践,因为它已经回答了您的问题。

If I understand correctly the class that I reference is supposed to be a Configuration class, not a regular spring service bean or component for example.

Is that right?



不,这并不完全正确。

提供给 @ContextConfiguration 的类(class)通常是 @Configuration类,但这不是必需的。

这是 JavaDoc for @ContextConfiguration 的摘录:

Annotated Classes

The term annotated class can refer to any of the following.

  • A class annotated with @Configuration
  • A component (i.e., a class annotated with @Component, @Service, @Repository, etc.)
  • A JSR-330 compliant class that is annotated with javax.inject annotations
  • Any other class that contains @Bean-methods


因此,您可以将任何“带注释的类”传递给 @ContextConfiguration .

Or is this indeed a valid way to achieve this goal?



实际上,这是实现该目标的有效方法;但是,加载 ApplicationContext 也有点不寻常。包含单个用户 bean。

问候,

Sam(Spring TestContext 框架的作者)

关于spring-boot - 仅使用一个 Bean 的 Spring 上下文测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51051994/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com