Luk*_* G. 5 java spring-boot spring-boot-test openfeign
我有一个 OpenFeign 客户端设置如下:
@FeignClient(name = "myService", qualifier = "myServiceClient", url = "${myservice.url}")
public interface MyServiceClient {
...
}
Run Code Online (Sandbox Code Playgroud)
Spring Boot 测试设置如下:
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = MyApplication.class)
@RunWith(SpringRunner.class)
@EnableFeignClients(clients = MyServiceClient .class)
public class ReservationSteps {
...
}
Run Code Online (Sandbox Code Playgroud)
该测试应该启动应用程序并使用 Feign 客户端向其发送请求。
问题是 RANDOM_PORT 值。
如何在属性文件中声明“myservice.url”属性,以便它包含正确的端口?
我已经尝试过这个:
myservice.url=localhost:${local.server.port}
Run Code Online (Sandbox Code Playgroud)
但结果是“localhost:0”。
我不想为端口使用常量值。
请帮忙。谢谢!
我知道这是一个老问题,但也许这个答案对某人有帮助
作为解决方法,我们可以做的是让主机解析为 Spring Ribbon。然后,您可以在测试开始之前动态配置主机。
首先,如果还没有maven依赖,请添加它
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
然后将测试配置为使用主机的“空”配置 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 {
...
}
Run Code Online (Sandbox Code Playgroud)
然后,在一个@Before方法中,我们需要做的就是向ribbon提供服务url,我们可以用一个简单的方法来做到这一点System.setProperty()
@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 {
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1602 次 |
| 最近记录: |