Mock server requests Espresso UI Android testing

I use Espresso to write UI tests for my Android application and would like to mock http requests using MockWebServer. I need to make fun of authentication responses and sign the user before running the tests.

Is there a way to force the application to use mockwebserver so that it will execute the actual requests, I can use respones installed on mockwebserver.

So far, I:

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 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()); } 
+4
source share
1 answer

In this example, replace the dependency with a dagger. But you can use any other DI approaches. The main idea is to replace the dependency during the test by providing a β€œtest” version of your application through a custom test runner.

+3
source

Source: https://habr.com/ru/post/1262368/


All Articles