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

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

用Dagger替换依赖关系的示例。但是您可以使用任何其他DI方法。主要思想-通过提供自定义测试运行器的“测试”版本应用程序,在测试期间替换依赖项。 - MyDogTom
我现在处于同样的情况,你有任何更新吗?你能实现这个吗?@yinjia - Emjey
1个回答

0
有点晚了,但如果需要一些参考的话。您必须配置客户端以与MockWebServer通信。MockWebServer侦听本地主机,也就是环回地址,而客户端在大多数情况下都配置为与原始API URL通信。
最干净的方法(在我看来)是创建一个构建变体或口味,其中每个构建包含一个不同的xml文件,指定URL。这样,您可以拥有一个与localhost通信的“模拟”构建,以及使用原始API URL的其他所有构建。
如果您需要示例,可以查看此处。在/app/src/mock/res/values/environment.xml下,您将看到以下资源。
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name" translatable="false">ExampleAndroidProject</string>
    <string name="imdb_base_url" translatable="false">http://127.0.0.1:8185</string>
    <string name="imdb_api_key" translatable="false">imdb_api_key</string>
</resources>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接