【问题标题】:Spring Boot Test: How To Use Only Certain Beans?Spring Boot 测试:如何仅使用某些 Bean?
【发布时间】:2021-01-16 22:12:10
【问题描述】:

我有带有一堆 bean 的 Spring Boot 应用程序。他们的数量每天都在增加。因此,我一直需要模拟新的 bean,否则测试将失败。所以,问题很简单:如何强制 Spring Boot 测试只使用应用上下文中的少数特定 bean,而不是全部

【问题讨论】:

  • 第一件事。 Is 是单元测试或集成测试。你想测试什么?
  • Spring Boot 单元测试
  • 您能说明您正在使用哪些注释吗?您很可能正在使用注释来运行集成测试 (@SpringBootTest),您绝对不应该这样做
  • 确实,@SpringBootTest

标签: spring spring-boot spring-test


【解决方案1】:

所以,我想通了:您需要在测试包中创建类并指向测试类以从那里运行 spring,并且您必须定义需要扫描哪些包以查找组件。为此,请使用前缀 scanBasePackages 或注释 @ComponentScan("packageForScan")

@SpringBootApplication(scanBasePackages = {"com.domain.folder1.package1","com.domain.folder1.package2"})
    public static class CustomApplicationRunner {
        public static void main(String[] args) {
            SpringApplication.run(CustomApplicationRunner.class, args);
        }
    }

在测试类中,你必须将这个类作为运行应用程序的主类。

@SpringBootTest(classes = MyTestClass.CustomApplicationRunner.class)
@RunWith(SpringRunner.class)
public class MyTestClass {//tests}

这是您可以包含或排除(使用注释@ComponentScan)添加到应用程序上下文中的任何包的方式。

【讨论】:

    猜你喜欢
    • 2019-07-22
    • 2019-01-18
    • 2022-01-19
    • 2017-10-23
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 2022-01-13
    相关资源
    最近更新 更多