unit-testing - 在不运行 @SpringBootApplication 的情况下测试 Spring Boot 服务

标签 unit-testing spring-boot

我有一个 Spring Boot 命令行应用程序:

    @SpringBootApplication
    public class TheApplication implements CommandLineRunner {
      public void run(String... args) throws Exception {
        ...
     }
    }

我想测试一个 @Service那个TheApplication使用。通常这很好,如果它是一个 mvc 应用程序,其中 TheApplication没有任何功能,但在本例中它是 CommandLineRunner每次我想测试一个 @Service , run被调用,导致测试出现问题。我需要将测试注释为 @Service用途 @Value配置自身,但这些注释会导致应用程序启动和 run要调用的方法。

有没有办法运行 Spring 启动测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class AccessTokenTest {
  ...
}

没有 TheApplication::run被调用?

最佳答案

事实证明,根据此 answer 相当容易.

@Configuration
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = CommandLineRunner.class))
@EnableAutoConfiguration
public class TestApplicationConfiguration {
}

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplicationConfiguration.class)
public class TheTest {
  @Autowired
  TheService theService;

  ...
}

关于unit-testing - 在不运行 @SpringBootApplication 的情况下测试 Spring Boot 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52777566/

相关文章:

java - IntelliJ Maven 项目中的特定 JUnit 测试失败

spring-boot - 使用 Spring Boot 2 和 Spring Security 5 进行多因素身份验证

mysql - 如何确保帐户的唯一性

java - 如何比较 Spring mongo 中的日期

javascript - 向模块添加新的 deps 时,AngularJS 测试失败

Django 在测试时保存了一个模型实例,但在真实数据库中找不到它

java - @Autowire JpaRepository 接口(interface)类错误限定 bean

java - 通过数据属性使用 javax.persistence.criteria 从结果集中删除重复项

javascript - 使用 Angular 服务 + Jasmine 进行 uni 测试 404 故障响应

unit-testing - 使用 Chutzpah 进行简单的 TypeScript 测试不起作用