测试 REST Api 模拟 http 服务器
Testing REST Api mock http server
我想测试连接到 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 但我不知道如何创建它)。感谢您的回答。如果您有更好的想法,我将不胜感激。
更新:
字符串响应是一个示例 reponse
您创建了一个 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);
我想测试连接到 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 但我不知道如何创建它)。感谢您的回答。如果您有更好的想法,我将不胜感激。
更新: 字符串响应是一个示例 reponse
您创建了一个 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);