【发布时间】:2015-08-02 21:33:08
【问题描述】:
我使用MockRestAdapter 在我的测试中返回模拟数据,但我也想测试错误(401、503、UnknownHostException 等)
对于SocketTimeoutException,有一个API,但是不同的响应码呢?
我已经尝试过MockWebServer,但无论我加入什么队列,我总是会从适配器获得 200 的模拟数据。
更新:我想像这样运行我的测试:
@RunWith(AndroidJUnit4.class)
@LargeTest
public class LoginActivityTest {
@Test public void goodCredentials() {
activity.login("username", "password");
assert(...); // Got back 200 and user object (from mock)
}
@Test public void wrongCredentials() {
activity.login("username", "wrong_password");
something.setResponse(401, "{error: wrong password}");
assert(...);
}
@Test public void someError() {
activity.login("username", "password");
something.setResponse(503, "{error: server error}");
assert(...);
}
}
更新 2:
发现了一些东西,相当丑陋,但可以满足我的需要:
MockApi implements ServiceApi {
public static Throwable throwable;
@Override login(Callback<User> callback) {
if (throwable != null) {
sendError(callback)
} else {
callback.success(new User("{name:test}"));
}
}
private void sendError(Callback callback) {
callback.failure(RetrofitError.unexpectedError("", throwable));
}
}
public class LoginActivityTest {
@Test public void someError() {
MockApi.throwable = new InterruptedIOException()
activity.login("username", "password");
// Assert having a time out message
}
@Test public void someError() {
MockApi.throwable = new UnknownHostException()
activity.login("username", "password");
// Assert having a no internet message
}
}
仍在努力,所以任何反馈都会有所帮助:)
【问题讨论】:
标签: android unit-testing mocking retrofit http-error