接受的答案具有主要思想。但我在某些方面挣扎,直到找出问题所在。所以我想用 Wiremock 来展示一个更完整的答案。
考试:
@ActiveProfiles("test")
@TestPropertySource(locations = "classpath:/application-test.yml")
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWireMock(port = 5001)
public class ZuulRoutesTest {
@LocalServerPort
private int port;
private TestRestTemplate restTemplate = new TestRestTemplate();
@Before
public void before() {
stubFor(get(urlPathEqualTo("/1/orders/")).willReturn(aResponse()
.withHeader("Content-Type", MediaType.TEXT_HTML_VALUE)
.withStatus(HttpStatus.OK.value())));
}
@Test
public void urlOrders() {
ResponseEntity<String> result = this.restTemplate.getForEntity("http://localhost:"+this.port +"/api/orders/", String.class);
assertEquals(HttpStatus.OK, result.getStatusCode());
verify(1, getRequestedFor(urlPathMatching("/1/.*")));
}
}
和application-test.yml
:
zuul:
prefix: /api
routes:
orders:
url: http://localhost:5001/1/
cards:
url: http://localhost:5001/2/
这应该有效。
但是 Wiremock 对我有一些限制。如果您在不同的端口上运行具有不同主机名的代理请求,如下所示:
zuul:
prefix: /api
routes:
orders:
url: http://lp-order-service:5001/
cards:
url: http://lp-card-service:5002/
在同一端口上运行的 localhost Wiremock 将无法为您提供帮助。我仍在尝试找到一个类似的集成测试,我可以在其中模拟来自 Spring 的 Bean,并url
在发出请求调用之前读取 Zuul 代理选择路由的内容。