我有一个 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/