如何在春季集成测试中启动应用程序?

时间:2018-09-27 13:39:21

标签: java spring-boot junit

我需要为我的应用创建集成测试。我使用了@SpringBootTest(classes = {Application.class})注解来启动它,但是启动它需要时间。那么,当我的应用程序准备就绪时,如何运行测试?

问题出在卡夫卡侦听器中:

@SpringBootApplication
public class Application {

   @Autowired
   private KafkaConsumeHandler kafkaConsumeHandler;

   public static void main(String[] args) {
       SpringApplication.run(Application.class, args);
   }

   @KafkaListener(topics =  "${kafka.topics.test}",  containerFactory = "kafkaListenerContainerFactory")
public void listenRegistred(KafkaMessage consumeKafka) {
        kafkaConsumeHandler.handleStartProcess(consumeKafka);
}

如果我尝试在测试中立即发送消息,则侦听器无法捕获它们。所以我在发送之前稍加停顿。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
@DirtiesContext
public class ProcessTest {   

@ClassRule
public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, "testTopic");

@Test
public void sendTestRegistred() throws Exception {
    Thread.sleep(5000); // Need a delay to boot an application
    ...
}

1 个答案:

答案 0 :(得分:1)

您需要添加用@SpringBootApplication注释的类。

示例:

@SpringBootApplication
public class SpringApp {}

@SpringBootTest(classes = SpringApp.class)
public class IntegrationTest {}

此外,请注意,集成测试总是比单元测试慢,并且您需要确定测试某种功能所需的测试类型。

有问题的更新后更新: 您的情况是由于等待KafkaEmbded启动而导致测试延迟。因此,您必须找到一种编程方式来确定Kafka准备就绪时的方式。这是应该可行的一种可能性:

@Before
public void setUp() throws Exception {
   // wait until the partitions are assigned
   for (MessageListenerContainer messageListenerContainer : 
        kafkaListenerEndpointRegistry.getListenerContainers()) {

       ContainerTestUtils.waitForAssignment(messageListenerContainer,
       embeddedKafka.getPartitionsPerTopic());
   }

代码从此处获取:https://github.com/code-not-found/spring-kafka/blob/master/spring-kafka-avro/src/test/java/com/codenotfound/kafka/SpringKafkaApplicationTest.java#L42 如果这样不起作用,请寻找如何等待KafkaEmbedded启动。您的问题不是由SpringBootTest引起的。