Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在spring集成测试中启动应用程序?_Java_Spring Boot_Junit - Fatal编程技术网

Java 如何在spring集成测试中启动应用程序?

Java 如何在spring集成测试中启动应用程序?,java,spring-boot,junit,Java,Spring Boot,Junit,我需要为我的应用程序创建一个集成测试。我使用@SpringBootTest(classes={Application.class})注释来引导它,但它的启动需要时间。那么,当我的应用程序准备就绪时,我如何运行测试呢 卡夫卡侦听器中存在问题: @SpringBootApplication public class Application { @Autowired private KafkaConsumeHandler kafkaConsumeHandler; public s

我需要为我的应用程序创建一个集成测试。我使用
@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
    ...
}

您需要添加用
@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());
   }
代码取自此处:
如果这不起作用,请查看如何等待
kafkamebedded
启动。您的问题不是由SpringBootTest引起的。

我使用了@SpringBootApplication类,我想测试它的API,但加载它需要时间,所以当我尝试发送请求时,我的应用程序还没有准备好接受它们。现在我在测试中使用Thread.sleep,我想对此进行更改。如果您在
@SpringBootTest
中有SpringBootApplication类,那么Spring Boot将在运行任何测试之前等待应用程序启动。您可以在这里生成一个示例应用程序,并验证这是默认行为。在你的例子中,你有一些其他的东西导致了一个问题,你需要从项目中提供更多的细节和代码,以使这成为一个有效的问题