Spring Boot WIREMOCK请求不匹配,HTTP方法和URL

7y4bm7vi  于 2023-06-22  发布在  Spring
关注(0)|答案(1)|浏览(176)

我正在与WIREMOCK一起编写一些测试。当我执行测试用例时,我得到下面的错误。
请求不匹配

Closest stub   | Request                                                  
GET              | CONNECT   <<<<< HTTP method does not match                                       
/greeting        | null      <<<<< URL does not match

这是我的代码。

public class HelloTest {
    @Autowired
    HelloDao HelloDao;
    @Test
    void testMethod() {
        String jsonResponse = """
                {
                   "version": {
                     "id": 22
                   }
                 }
                """;
        WIREMOCK.stubFor(get("/greeting").willReturn(aResponse().withStatus(HttpStatus.OK.value())
                .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .withBody(jsonResponse)));
        var response = assertInstanceOf(HelloResp.class, HelloDao.getGreeting());
    }
}

public HelloResp getGreeting() {
    CompletableFuture<HelloResp> future = HelloAsyncDao.getGreeting();
    return ExternalApiUtils.joinFuture(future, HelloProperties.VERSION_API);
}

public CompletableFuture<HelloResp> getGreeting() {
    String urlPart = "/greeting";
    HttpRequest httpRequest = HttpRequest.builder(urlPart).get().addHeaders(generateHttpHeaders()).build();
    return httpService.execute(httpRequest, helloProperties.getHttp(),HelloProperties.VERSION_API, HelloResponseMapper::mapHelloRespResp);
}

我更改了URI并尝试了一些试错方法。我不知道这个错误是如何发生的,因为我是相当新的wiremock。如果能帮上忙我会很感激的。先谢谢你。

kkbh8khc

kkbh8khc1#

您应该在之前设置wiremock并使用spring Boot test annotations。下面是一个工作示例:

@SpringBootTest
@AutoConfigureMockMvc
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)
abstract class UserControllerIntegrationTestSupport {

  WireMockServer wireMockServer = new WireMockServer(3000);

@Autowired protected ObjectMapper objectMapper;

  @BeforeEach
  void setupBeforeEach() throws Exception {

     
      List<UserDTO> mockUserDTOs =
        Arrays.asList(
            new UserDTO(1L, "User1", "user1@example.com", "username1"),
            new UserDTO(2L, "User2", "user2@example.com", "username2"));

    RestPageResponse<UserDTO> pageResponse = new RestPageResponse<>(mockUserDTOs);

    String jsonResponse = objectMapper.writeValueAsString(pageResponse);

    // wiremock setup

    wireMockServer.start();

    WireMock.configureFor("localhost", wireMockServer.port());
    stubFor(
        get(urlEqualTo("/mock/user"))
            .willReturn(
                aResponse().withHeader("Content-Type", "application/json").withBody(jsonResponse)));
  }

  @AfterEach
  void tearDownAfterEach() {
    
    wireMockServer.stop();
  }

l

相关问题