模拟服务器请求Android Espresso UI测试 [英] Mock server requests Android Espresso UI Testing

查看:99
本文介绍了模拟服务器请求Android Espresso UI测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Espresso为我的Android应用程序编写UI测试,并想使用MockWebServer模拟HTTP请求. 在运行测试之前,我需要模拟身份验证响应并登录用户.

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.

到目前为止,我有:

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());
}

推荐答案

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.

这篇关于模拟服务器请求Android Espresso UI测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆