2

我无法让MockWebServer正常工作。我将依赖项添加到 build.gradle

testImplementation 'com.squareup.okhttp3:mockwebserver:4.2.0'

我有以下课程(我从这里复制https://codingtim.github.io/webclient-testing/

public class ApiCaller {

private WebClient webClient;

ApiCaller(WebClient webClient) {
    this.webClient = webClient;
}

Mono<String> callApi() {
    return webClient.put()
            .uri("/api/resource")
            .contentType(MediaType.APPLICATION_JSON)
            .header("Authorization", "customAuth")
            .syncBody(new String())
            .retrieve()
            .bodyToMono(SimpleResponseDto.class);
    }
}

我的测试课看起来像这样

public class ApiCallerTest {

private final MockWebServer mockWebServer = new MockWebServer();
private final ApiCaller apiCaller = new ApiCaller(WebClient.create(mockWebServer.url("/").toString()));

@AfterEach
void tearDown() throws IOException {
    mockWebServer.shutdown();
}

@Test
void call() throws InterruptedException {
    mockWebServer.enqueue(
            new MockResponse()
                    .setResponseCode(200)
                    .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                    .setBody("{\"y\": \"value for y\", \"z\": 789}")
    );
    SimpleResponseDto response = apiCaller.callApi().block();
    assertThat(response, is(not(nullValue())));
    assertThat(response.getY(), is("value for y"));
    assertThat(response.getZ(), is(789));

    RecordedRequest recordedRequest = mockWebServer.takeRequest();
    //use method provided by MockWebServer to assert the request header
    recordedRequest.getHeader("Authorization").equals("customAuth");
    DocumentContext context = JsonPath.parse(recordedRequest.getBody().inputStream());
    //use JsonPath library to assert the request body
    assertThat(context, isJson(allOf(
            withJsonPath("$.a", is("value1")),
            withJsonPath("$.b", is(123))
    )));
    }
}

但是,当我尝试运行测试时出现以下错误

ApiCallerTest.java:19:错误:无法访问 ExternalResource private final ApiCaller apiCaller = new ApiCaller(WebClient.create(mockWebServer.url("/").toString()));

知道可能出了什么问题吗?

4

0 回答 0