【问题标题】:Testing a spring boot service without running @SpringBootApplication在不运行 @SpringBootApplication 的情况下测试 Spring Boot 服务
【发布时间】:2019-03-17 13:39:54
【问题描述】:

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

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

我想测试TheApplication 使用的@Service。通常,如果它是一个 mvc 应用程序,其中 TheApplication 没有任何功能,但在这种情况下它是一个 CommandLineRunner 并且每次我想测试一个 @Servicerun 都会被调用,这会产生问题测试。我需要注释测试,因为@Service 使用@Value 来配置自身,但是这些注释会导致应用程序启动并调用run 方法。

有没有办法运行 Spring Boot 测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class AccessTokenTest {
  ...
}

没有TheApplication::run 被调用?

【问题讨论】:

  • 其实@SpringBootTest唤醒了上下文,所以调用了.run()方法。您可以随意省略注释以在没有上下文的情况下测试组件

标签: unit-testing spring-boot


【解决方案1】:

事实证明,根据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;

  ...
}

【讨论】:

    猜你喜欢
    • 2019-09-23
    • 2020-04-03
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 2015-06-07
    • 2017-07-06
    相关资源
    最近更新 更多