问题
I am using Espresso to write UI tests for my Android application and would like to mock http requests using MockWebServer. I need to mock authentication responses and sign in the user before the tests are run.
Is there a way make the app use mockwebserver so that isntead of making actual requests, I can use respontes enqueued on mockwebserver.
So far I have:
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());
}
回答1:
This example of replacing dependency with Dagger. But you can use any other approaches for DI. Main idea - replace dependency during test by providing a "test" version of you application via custom test runner.
来源:https://stackoverflow.com/questions/41386652/mock-server-requests-android-espresso-ui-testing