не может получить доступ к ExternalResource при вызове MockWebServer - PullRequest
0 голосов
/ 25 сентября 2019

У меня проблемы с работой 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 apiCaller apiCaller = new ApiCaller (WebClient.create (mockWebServer.url ("/"). ToString ()));

Есть идеи, что может быть не так?

...