在iOS中,我可以像这样进行集成测试
// Setup expecttation to prevent from test ending before all async tasks finish.
let expectation = expectationWithDescription("Sign in");
// call API method for signing in
PersonAPI.signIn("asdf@asdf.co", password: "Free Milk Lane", done:{(response: APIResponse)->Void in
// check response for errors
XCTAssertTrue(response.isSuccessful() == true, response.getMessage());
// mark async operation is completed
expectation.fulfill();
});
// wait until all async operations completed
waitForExpectationsWithTimeout(5.0, handler:nil);
但在Android中它并不那么明显。现在我正在尝试使用Roboelectric& amp;改造,但它只是不想合作。我已经尝试了很多东西,我认为这个问题与如何汇集线程有关。例如,以下代码将通过,但无论如何都会等待5秒,即使API调用可能只需要1秒钟:
// Setup signal to prevent from test ending before all async tasks finish.
final CountDownLatch signal = new CountDownLatch(1);
// call API method for signing in
PersonAPI.signIn("asdf@asdf.co", "Free Milk Lane", new IAPICallback() {public void done(APIResponse response) {
// check response for errors
Assert.assertTrue(response.getMessage(), response.isSuccessful());
// mark async operation is completed
signal.countDown();
}});
// wait until all async operations completed
signal.await(5, TimeUnit.SECONDS);
此时我愿意尝试任何事情(除了嘲笑)。改变改造,重新电动,无论如何。
再次感谢
答案 0 :(得分:0)
这就是我如何运作的方式。我改变了改造以进行同步调用。然后我将响应存储在静态变量中并在主线程上完成断言。
public class PersonAPITest {
private static APIResponse _response = null;
@Test
public void testSignIn() {
// Setup signal to prevent from test ending before all async tasks finish.
final CountDownLatch signal = new CountDownLatch(1);
// call API method for signing in
PersonAPI.signIn("asdf@asdf.co", "Free Milk Lane", new IAPICallback() {public void done(APIResponse response) {
// check response for errors
PersonAPITest._response = response;
// mark async operation is completed
signal.countDown();
}});
// wait until all async operations completed
signal.await(5, TimeUnit.SECONDS);
Assert.assertTrue(PersonAPITest._response.getMessage(), PersonAPITest._response.isSuccessful());
}
}
改装代码的示例如下。基本上我只使用本机Java多线程来创建异步方法:
public static void getGoogle(final IAPICallback callback) {
new Thread(new Runnable() {
@Override
public void run() {
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint("http://google.com")
.setClient(new OkClient(new OkHttpClient()));
RestAdapter adapter = builder.build();
ITaskAPI service = (ITaskAPI) adapter.create(ITaskAPI.class);
Response result = service.getGoogle();
APIResponse response;
if(result.getStatus() == 200) {
response = new APIResponse(true, "it worked!");
}else{
response = new APIResponse(false, "boo! bad dog!");
}
callback.done(response);
}
}).start();
}