模拟服务器请求Android Espresso UI测试

时间:2016-12-29 20:21:39

标签: android-espresso android-testing okhttp3 mockwebserver

我正在使用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());
}

1 个答案:

答案 0 :(得分:4)

This example用Dagger取代依赖。但您可以使用任何其他方法进行DI。主要思想 - 通过自定义测试运行器提供应用程序的“测试”版本来替换测试期间的依赖性。