spring boot测试未使用测试属性

vatpfxk5  于 2021-06-08  发布在  Kafka
关注(0)|答案(1)|浏览(448)

我使用的是springboot2.0.1,但是当我执行测试时,它似乎开始了,在测试类之前,也是主类。在我的主类中,我使用spring云配置、发现服务和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和springclouddiscovery的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
fumotvh3

fumotvh31#

我认为你的问题在于 @SpringBootTest 它用主应用程序加载主应用程序上下文 ConfigurationClass . 因此,即使您没有使用kafka,spring也会尝试初始化缺少的kafka bean: spring.kafka.bootstrap-servers 财产。
您可以通过指定一个单独的配置类来运行测试,而不必使用kafka bean和其他不必要的bean @ContextConfiguration ```
@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);
}

}

相关问题