我正在尝试为我的 Android 应用程序运行 Espresso 测试,但有一个问题一直困扰着我。在MainActivity中,某些 View 的可见性取决于从网络加载的数据,但在MainActivityTest中,我无法操纵加载数据的过程,所以我不知道真实的数据以及哪个 View 应该显示,哪个 View 不应该显示。结果,我不知道如何继续我的测试。谁能告诉我如何处理这种情况?谢谢!
最佳答案
尝试使用MockWebServer图书馆。它允许您在测试中模拟 http 响应,如下所示:
/**
* Constructor for the test. Set up the mock web server here, so that the base
* URL for the application can be changed before the application loads
*/
public MyActivityTest() {
MockWebServer server = new MockWebServer();
try {
server.start();
} catch (IOException e) {
e.printStackTrace();
}
//Set the base URL for the application
MyApplication.sBaseUrl = server.url("/").toString();
//Create a dispatcher to handle requests to the mock web server
Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest recordedRequest) throws InterruptedException {
try {
//When the activity requests the profile data, send it this
if(recordedRequest.getPath().startsWith("/users/self")) {
String fileName = "profile_200.json";
InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
String jsonString = new String(ByteStreams.toByteArray(in));
return new MockResponse().setResponseCode(200).setBody(jsonString);
}
//When the activity requests the image data, send it this
if(recordedRequest.getPath().startsWith("/users/self/media/recent")) {
String fileName = "media_collection_model_test.json";
InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
String jsonString = new String(ByteStreams.toByteArray(in));
return new MockResponse().setResponseCode(200).setBody(jsonString);
}
} catch (IOException e) {
e.printStackTrace();
}
return new MockResponse().setResponseCode(404);
}
};
server.setDispatcher(dispatcher);
}
关于java - 在 Android 中使用 Espresso 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43485077/