我正在使用 Espresso 为我的 Android 应用程序编写 UI 测试,并想使用 MockWebServer 模拟 http 请求。在运行测试之前,我需要模拟身份验证响应并登录用户。
有没有办法让应用程序使用mockwebserver,而不是发出实际请求,我可以使用mockwebserver上排队的响应。
到目前为止,我有:
public class AuthenticationTest {
@Rule
public ActivityTestRule<Authentication> mActivityTestRule = new ActivityTestRule<>(Authentication.class);
private Authentication activity;
private MockWebServer server;
@Before
public void signin() throws Exception {
server = new MockWebServer();
server.start();
activity = mActivityTestRule.getActivity();
MyApplication.State state = activity.getState();
String serverUrl = server.url("/").toString();
// Here is where I have a problem. How to force client to use mock server?
}
@Test
public void firstTest() {
String contentType = "Content-type: application/json";
MockResponse r1 = new MockResponse().setResponseCode(200).setBody("example_body").addHeader(contentType);
server.enqueue(r1);
// typing credentials and pressing "Sign in" button, which should use mocked server's response:
ViewInteraction email = onView(allOf(withId(R.id.emailAddress), isDisplayed()));
email.perform(replaceText("some_email@test.com"), closeSoftKeyboard());
ViewInteraction password = onView(allOf(withId(R.id.password), isDisplayed()));
password.perform(replaceText("some_password"), closeSoftKeyboard());
ViewInteraction signin = onView(allOf(withId(R.id.signInButton), withText("Sign In"), isDisplayed()));
button2.perform(click());
}