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

2023-11-25

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

有没有办法让应用程序使用mockwebserver,这样我就可以在mockwebserver 上使用respondus enqueue,而不是发出实际请求。

到目前为止我有:

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("[email protected]"), 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());
}

参加聚会有点晚了,但以防万一需要一些参考。您必须配置客户端才能与 MockWebServer 进行通信。 MockWebServer 在 localhost 上监听。环回地址,在您的情况下,客户端很可能配置为与原始 API url 进行通信。

实现此目的的最干净的方法 (IMO) 是创建一个构建变体或风格,其中每个构建都包含一个不同的 xml 文件来说明 url。这样,您就可以拥有与 localhost 通信的“模拟”构建,以及使用原始 API url 的所有其他构建。

如果需要示例可以看一下here. Under /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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

模拟服务器请求 Android Espresso UI 测试 的相关文章

随机推荐