yin*_*jia 6 android-testing android-espresso mockwebserver okhttp3
我正在使用 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());
}
Run Code Online (Sandbox Code Playgroud)
参加聚会有点晚了,但以防万一需要一些参考。您必须配置客户端才能与 MockWebServer 进行通信。MockWebServer 在 localhost 上监听。环回地址,在您的情况下,客户端很可能配置为与原始 API url 进行通信。
实现此目的的最干净的方法 (IMO) 是创建一个构建变体或风格,其中每个构建都包含一个不同的 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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5026 次 |
最近记录: |