0

我有一个本地运行的休息端点,我正在尝试使用 Spring WebClient 与之通信。作为测试目的的第一步,我正在尝试使用 Spring WebTestClient。我的本地休息端点在特定端口上运行(比如说 8068)。我的假设是,由于端口是固定的,我应该使用:

SpringBootTest.WebEnvironment.DEFINED_PORT

,然后以某种方式在我的代码中指定该端口是什么。但是我不知道该怎么做。它似乎默认为 8080。这是我的代码的重要部分:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SpringWebclientApplicationTests {

@Autowired
private WebTestClient webTestClient;

@Test
public void wcTest() throws Exception {

    String fullUri = "/services/myEndpoint/v1?userIds=jsmith&objectType=DEFAULT";

    WebTestClient.ResponseSpec responseSpec1 = webTestClient.get().uri(fullUri, "").exchange().expectStatus().isOk();
}

该测试预计返回“200 OK”,但返回“404 NOT_FOUND”。错误响应中显示的请求是:

GET http://localhost:8080/services/myEndpoint/v1?userIds=jsmith&objectType=DEFAULT

,显然是因为它默认为 8080,而我需要它是 8068。我会感谢任何可以解释正确定义端口的人。谢谢。

4

1 回答 1

0

我想到了。我不相信你应该使用

SpringBootTest.WebEnvironment.DEFINED_PORT

除非端点正在监听 8080。在我的情况下,由于我需要使用我无法控制的端口号,所以我这样做了:

@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SpringWebclientApplicationTests {

    private WebTestClient client;

    @Before
    public void setup() {
        String baseUri = "http://localhost:" + "8079";
        this.client = WebTestClient.bindToServer().baseUrl(baseUri).build();
    }

    @Test
    public void wcTest() throws Exception {

    String fullUri = "/services/myEndpoint/v1?userIds=jsmith&objectType=DEFAULT";
    WebTestClient.ResponseSpec responseSpec1 = client.get().uri(fullUri, "").exchange().expectStatus().isOk();
    }
}

,我使用 bindToServer 方法在本地实例化 webtestclient,而不是作为自动装配的 bean,并删除:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)

,所以它现在工作正常。

于 2020-11-15T17:56:44.413 回答