我有一个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“。
我不想对端口使用常量值。
请帮帮忙。谢谢!
发布于 2020-03-22 17:00:06
我知道这是一个古老的问题,但也许这个答案会对某些人有所帮助。
作为一种解决办法,我们可以做的是让主机解析到Spring Ribbon。然后,您将在测试开始之前动态配置主机。
首先,如果您还没有maven依赖项,请添加它
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<scope>test</scope>
</dependency>然后配置您的测试,使其使用主机的“空”配置url运行,这里是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 {
...
}然后,在@Before方法中,我们所需要做的就是提供指向ribbon的服务url,我们可以通过一个简单的System.setProperty()来实现这一点
public class MyTest {
@LocalServerPort
private int port;
@Before
public void setup() {
System.setProperty("MyServiceClient.ribbon.listOfServers", "http://localhost:" + port);
...
}https://stackoverflow.com/questions/58539366
复制相似问题