Test中的默认Spring

Test中的默认Spring

本文介绍了使用动态值覆盖Junit Test中的默认Spring-Boot application.properties设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想覆盖测试中application.properties中定义的属性,但@TestPropertySource只允许提供预定义的值。



我需要的是启动服务器随机端口N,然后将此端口传递给spring-boot应用程序。该端口必须是短暂的,以允许同时在同一主机上运行多个测试。



我不是指嵌入式http服务器(jetty),而是一些在测试开始时启动的不同服务器(例如zookeeper)和正在测试的应用程序必须连接到它。



实现此目的的最佳方法是什么? / p>

(这是一个类似的问题,但答案没有提到临时端口的解决方案 - )

解决方案

您可以在 @BeforeClass 中覆盖port属性的值,如下所示:

  @BeforeClass 
public static void beforeClass(){
System.setProperty(zookeeper.port,getRandomPort());
}


I want to override properties defined in application.properties in tests, but @TestPropertySource only allows to provide predefined values.

What I need is to start a server on a random port N, then pass this port to spring-boot application. The port has to be ephemeral to allow running multiple tests on the same host at the same time.

I don't mean the embedded http server (jetty), but some different server that is started at the beginning of the test (e.g. zookeeper) and the application being tested has to connect to it.

What's the best way to achieve this?

(here's a similar question, but answers do not mention a solution for ephemeral ports - Override default Spring-Boot application.properties settings in Junit Test)

解决方案

You could override the value of the port property in the @BeforeClass like this:

@BeforeClass
public static void beforeClass() {
    System.setProperty("zookeeper.port", getRandomPort());
}

这篇关于使用动态值覆盖Junit Test中的默认Spring-Boot application.properties设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 19:02