我正在使用 spring boot 2.0.1 ,但是当我执行测试时,它似乎在测试类之前开始,也是主类。 在我的主课中,我使用 spring cloud config、discovery service 和 kafka。 我有这个测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations = "classpath:bootstrap-test.properties")
@ActiveProfiles("test")
public class DaemonLogServiceTest {
@Autowired
private LogService logService;
@Before
public void setUp() {
ResultLog log = new ResultLog();
log.setNumberOfRowsProcessed(10);
log.setLastCodOperProcessed(1000);
log.setStatus(Status.SUCCESS.name());
}
@Test
public void whenOperationsProcessedThenLog() {
logService.newActivity(10, 1000L, Status.SUCCESS);
ResultLog log = logService.saveActivity();
Assert.assertNotNull(log);
}
}
当我运行它时,它似乎启动了使用 Kafka 和 Spring 云发现的 Main 方法(不是来自测试)。 这是输出:
018-06-19 14:45:01.397 ERROR 17124 --- [ main] o.s.boot.SpringApplication : Application run failed
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at []
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.kafka.bootstrap-servers' in value "${spring.kafka.bootstrap-servers}"
我只在主应用程序中使用 Kafka,而不是在测试类中。 我的属性文件是:
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.schema=classpath:schema.sql
daemon.delay=2000
spring.cloud.discovery.enabled = false
spring.cloud.config.discovery.enabled = false
spring.cloud.config.enabled = false
eureka.client.enabled=false
spring.profiles.active=test
最佳答案
我认为你的问题在于@SpringBootTest
它用你的主ConfigurationClass
加载你的主应用程序上下文.因此,即使您没有使用 Kafka,Spring 也会尝试初始化您缺少的 kafka bean:spring.kafka.bootstrap-servers
属性(property)。
您可以通过使用 @ContextConfiguration
指定一个单独的配置类来运行您的测试,而无需使用 kafka bean 和其他不必要的 bean|
@RunWith(SpringRunner.class)
@TestPropertySource(locations = "classpath:bootstrap-test.properties")
@ContextConfiguration(classes = LogServiceTestConfig.class)
public class DaemonLogServiceTest {
@Autowired
private LogService logService;
@Before
public void setUp() {
ResultLog log = new ResultLog();
log.setNumberOfRowsProcessed(10);
log.setLastCodOperProcessed(1000);
log.setStatus(Status.SUCCESS.name());
}
@Test
public void whenOperationsProcessedThenLog() {
logService.newActivity(10, 1000L, Status.SUCCESS);
ResultLog log = logService.saveActivity();
Assert.assertNotNull(log);
}
}
关于Spring Boot 测试未使用测试属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50929094/