spring boot测试未使用测试属性

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

我使用的是springboot2.0.1,但是当我执行测试时,它似乎开始了,在测试类之前,也是主类。在我的主类中,我使用spring云配置、发现服务和kafka。我有一个测试班:

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. @TestPropertySource(locations = "classpath:bootstrap-test.properties")
  4. @ActiveProfiles("test")
  5. public class DaemonLogServiceTest {
  6. @Autowired
  7. private LogService logService;
  8. @Before
  9. public void setUp() {
  10. ResultLog log = new ResultLog();
  11. log.setNumberOfRowsProcessed(10);
  12. log.setLastCodOperProcessed(1000);
  13. log.setStatus(Status.SUCCESS.name());
  14. }
  15. @Test
  16. public void whenOperationsProcessedThenLog() {
  17. logService.newActivity(10, 1000L, Status.SUCCESS);
  18. ResultLog log = logService.saveActivity();
  19. Assert.assertNotNull(log);
  20. }
  21. }

当我运行它时,它似乎启动了使用kafka和springclouddiscovery的main方法(而不是来自测试)。以下是输出:

  1. 018-06-19 14:45:01.397 ERROR 17124 --- [ main] o.s.boot.SpringApplication : Application run failed
  2. java.lang.IllegalStateException: Failed to load ApplicationContext
  3. at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
  4. at []
  5. Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.kafka.bootstrap-servers' in value "${spring.kafka.bootstrap-servers}"

我只在主应用程序中使用kafka,不在测试类中使用。我的属性文件是:

  1. spring.datasource.driver-class-name=org.h2.Driver
  2. spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
  3. spring.datasource.username=sa
  4. spring.datasource.password=sa
  5. spring.datasource.schema=classpath:schema.sql
  6. daemon.delay=2000
  7. spring.cloud.discovery.enabled = false
  8. spring.cloud.config.discovery.enabled = false
  9. spring.cloud.config.enabled = false
  10. eureka.client.enabled=false
  11. 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);
}

}

展开查看全部

相关问题