我有一个这样的OpenFeign客户端设置:
@FeignClient(name = "myService", qualifier = "myServiceClient", url = "${myservice.url}")
public interface MyServiceClient {
...
}
和这样的Spring Boot测试设置:
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = MyApplication.class)
@RunWith(SpringRunner.class)
@EnableFeignClients(clients = MyServiceClient .class)
public class ReservationSteps {
...
}
该测试应该可以启动应用程序并使用Feign客户端向其发送请求。
问题出在RANDOM_PORT值上。
如何在属性文件中声明“ myservice.url”属性,使其包含正确的端口?
我已经尝试过了:
myservice.url=localhost:${local.server.port}
但结果为“ localhost:0”。
我不想为端口使用恒定值。
请帮助。谢谢!
答案 0 :(得分:1)
我知道这是一个老问题,但是也许这个答案对某人会有帮助
作为一种解决方法,我们可以做的是让主机解析为Spring Ribbon。然后,您可以在测试开始之前动态配置主机。
首先,添加尚未具备的Maven依赖项
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<scope>test</scope>
</dependency>
然后将测试配置为使用主机的“空”配置网址运行,该网址为myservice.url
属性
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = MyApplication.class)
@RunWith(SpringRunner.class)
@EnableFeignClients(clients = MyServiceClient.class)
@TestPropertySource(properties = "myservice.url=") // this makes sure we do the server lookup with ribbon
public class MyTest {
...
}
然后,在@Beofre
方法中,我们要做的就是提供功能区的服务URL,我们可以使用简单的System.setProperty()
public class MyTest {
@LocalServerPort
private int port;
@Before
public void setup() {
System.setProperty("MyServiceClient.ribbon.listOfServers", "http://localhost:" + port);
...
}