简体   繁体   中英

Testing REST Api mock http server

I would like to test an application that connects to Github api, download some records and do something with them. I want to have a mock object and I did something like that:

@SpringBootTest
public class GithubApiTest
{
    GithubApiClient githubApiClient;

    @Mock
    HttpClient httpClient;

    HttpRequest httpRequest;

    @Value("response.json")
    private String response;

    @BeforeTestClass
    void init() throws IOException, InterruptedException {
        HttpRequest request = HttpRequest.newBuilder()
                .GET()
                .uri(URI.create("https://api.github.com/repos/owner/reponame"))
                .build();
        githubApiClient = new GithubApiClient(httpClient);
        Mockito.when(httpClient.send(request, HttpResponse.BodyHandlers.ofString())).thenReturn(<here>
        );

        githubApiClient = new GithubApiClient(httpClient);
    }
}

Looks it good? What should I put into thenReturn (it needs a HttpResponse but I dont know how to create this). Thanks for your answers. If you have any better ideas I will be grateful.

Update: String response is a example reponse

You create a mocked response of type HttpResponse. The mockedResponse will have status code 200, and the response body is "ExampleOfAResponseBody" which is of type String which you requested.

import java.net.http.HttpResponse;


HttpResponse<String> mockedResponse = Mockito.mock(HttpResponse.class);
Mockito.when(mockedResponse.statusCode()).thenReturn(200);
Mockito.when(mockedResponse.body()).thenReturn("ExampleOfAResponseBody");
    
Mockito.when(httpClient.send(request, HttpResponse.BodyHandlers.ofString())).thenReturn(mockedResponse);
       

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM