我可以测试retrofit2beta4的真实反应吗?我需要Mockito还是Robolectic?
我的项目中没有活动,它将是一个库,我需要测试服务器是否正确响应。 现在我有这样的代码而且卡住了......
@Mock
ApiManager apiManager;
@Captor
private ArgumentCaptor<ApiCallback<Void>> cb;
@Before
public void setUp() throws Exception {
apiManager = ApiManager.getInstance();
MockitoAnnotations.initMocks(this);
}
@Test
public void test_login() {
Mockito.verify(apiManager)
.loginUser(Mockito.eq(login), Mockito.eq(pass), cb.capture());
// cb.getValue();
// assertEquals(cb.getValue().isError(), false);
}
我可以做出虚假回应,但我需要测试真实。它成功了吗?它的身体是否正确? 你能帮我解决一下代码吗?
答案 0 :(得分:104)
测试真实服务器请求通常不是一个好主意。有关该主题的有趣讨论,请参阅this blog post。据作者说,使用真实的服务器是一个问题,因为:
- 另一个可以间歇性失败的移动件
- 需要Android域以外的一些专业知识来部署服务器并保持更新
- 难以触发错误/边缘情况
- 测试执行缓慢(仍在进行HTTP调用)
您可以使用模拟服务器(例如OkHttp&#39; MockWebServer来模拟真实的响应结果,从而避免上述所有问题。例如:
@Test
public void test() throws IOException {
MockWebServer mockWebServer = new MockWebServer();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(mockWebServer.url("").toString())
//TODO Add your Retrofit parameters here
.build();
//Set a response for retrofit to handle. You can copy a sample
//response from your server to simulate a correct result or an error.
//MockResponse can also be customized with different parameters
//to match your test needs
mockWebServer.enqueue(new MockResponse().setBody("your json body"));
YourRetrofitService service = retrofit.create(YourRetrofitService.class);
//With your service created you can now call its method that should
//consume the MockResponse above. You can then use the desired
//assertion to check if the result is as expected. For example:
Call<YourObject> call = service.getYourObject();
assertTrue(call.execute() != null);
//Finish web server
mockWebServer.shutdown();
}
如果您需要模拟网络延迟,可以按如下方式自定义响应:
MockResponse response = new MockResponse()
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("Cache-Control", "no-cache")
.setBody("{}");
response.throttleBody(1024, 1, TimeUnit.SECONDS);
或者,您可以使用MockRetrofit
和NetworkBehavior
来模拟API响应。请参阅here如何使用它的示例。
最后,如果您只是想测试您的Retrofit服务,最简单的方法是创建一个模拟版本,为您的测试发出模拟结果。例如,如果您有以下GitHub
服务接口:
public interface GitHub {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> contributors(
@Path("owner") String owner,
@Path("repo") String repo);
}
然后,您可以为测试创建以下MockGitHub
:
public class MockGitHub implements GitHub {
private final BehaviorDelegate<GitHub> delegate;
private final Map<String, Map<String, List<Contributor>>> ownerRepoContributors;
public MockGitHub(BehaviorDelegate<GitHub> delegate) {
this.delegate = delegate;
ownerRepoContributors = new LinkedHashMap<>();
// Seed some mock data.
addContributor("square", "retrofit", "John Doe", 12);
addContributor("square", "retrofit", "Bob Smith", 2);
addContributor("square", "retrofit", "Big Bird", 40);
addContributor("square", "picasso", "Proposition Joe", 39);
addContributor("square", "picasso", "Keiser Soze", 152);
}
@Override public Call<List<Contributor>> contributors(String owner, String repo) {
List<Contributor> response = Collections.emptyList();
Map<String, List<Contributor>> repoContributors = ownerRepoContributors.get(owner);
if (repoContributors != null) {
List<Contributor> contributors = repoContributors.get(repo);
if (contributors != null) {
response = contributors;
}
}
return delegate.returningResponse(response).contributors(owner, repo);
}
}
然后,您可以在测试中使用MockGitHub
来模拟您要查找的各种回复。有关完整示例,请参阅此SimpleService的SimpleMockService和Retrofit example的实现。
说完这一切之后,如果你绝对必须连接到实际的服务器,你可以设置Retrofit与自定义ImmediateExecutor
同步工作:
public class ImmediateExecutor implements Executor {
@Override public void execute(Runnable command) {
command.run();
}
}
然后将其应用于构建Retrofit时使用的OkHttpClient
:
OkHttpClient client = OkHttpClient.Builder()
.dispatcher(new Dispatcher(new ImmediateExecutor()))
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
//Your params
.build();
答案 1 :(得分:17)
答案太容易了:
使用CountDownLatch使您的测试等到调用countDown()
public class SimpleRetrofitTest {
private static final String login = "your@login";
private static final String pass = "pass";
private final CountDownLatch latch = new CountDownLatch(1);
private ApiManager apiManager;
private OAuthToken oAuthToken;
@Before
public void beforeTest() {
apiManager = ApiManager.getInstance();
}
@Test
public void test_login() throws InterruptedException {
Assert.assertNotNull(apiManager);
apiManager.loginUser(login, pass, new ApiCallback<OAuthToken>() {
@Override
public void onSuccess(OAuthToken token) {
oAuthToken = token;
latch.countDown();
}
@Override
public void onFailure(@ResultCode.Code int errorCode, String errorMessage) {
latch.countDown();
}
});
latch.await();
Assert.assertNotNull(oAuthToken);
}
@After
public void afterTest() {
oAuthToken = null;
}}
答案 2 :(得分:0)
除非您正在测试QA服务器API,否则出于某些原因这是个坏主意。
使用Mockito的最佳方式,或模拟您的回复
此外,如果您必须测试生产API,请测试一次并添加@Ignore注释。这样他们就不会一直运行,也不会使用虚假数据向您的服务器发送垃圾邮件,只要您觉得api没有正常运行,就可以使用它。