测试REST Api模拟http服务器



我想测试一个连接到Github api的应用程序,下载一些记录并与它们做一些事情。我想要一个模拟对象,我这样做了:

@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);
}
}

看起来不错吗?我应该把什么放入thenReturn(它需要一个HttpResponse,但我不知道如何创建这个)。谢谢你的回答。如果你有更好的主意,我将不胜感激。

更新:字符串响应是一个示例响应

创建HttpResponse类型的模拟响应。mockedResponse的状态码为200,响应体为exampleofaresponsebody;

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);

最新更新