Integrate Espresso UI testing with MockWebServer
จากในหัวข้อที่แล้ว เราได้ทำการเตรียม Server จำลองด้วย MockWebServer เรียบร้อยแล้ว ในหัวข้อนี้ก็จะเป็นการ ทำการทดสอบด้วย Espresso
- เริ่มจากการสั่งให้ Android start app ขึ้นมาก่อน
@RunWith(AndroidJUnit4.class)
public class LoginMockServerTest {
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule(MainActivity.class, true, false);
private MockWebServer server;
@Before
public void setUp() throws Exception {
server = new MockWebServer();
server.start();
LoginAPIEndpoint.BASE_URL = server.url("/").toString();
}
@Test
public void loginSuccess() {
server.enqueue(new MockResponse().setResponseCode(200));
Intent intent = new Intent();
mActivityRule.launchActivity(intent);
}
- ใส่ username, password, กดปุ่ม ตกลง แล้วตรวจสอบดูว่า เข้าสู่หน้า Welcome ถูกต้องหรือไม่
@RunWith(AndroidJUnit4.class)
public class LoginMockServerTest {
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule(MainActivity.class, true, false);
private MockWebServer server;
@Before
public void setUp() throws Exception {
server = new MockWebServer();
server.start();
LoginAPIEndpoint.BASE_URL = server.url("/").toString();
}
@Test
public void loginSuccess() {
server.enqueue(new MockResponse().setResponseCode(200));
Intent intent = new Intent();
mActivityRule.launchActivity(intent);
onView(withId(R.id.username)).perform(typeText("username"));
onView(withId(R.id.password)).perform(typeText("password"));
onView(withId(R.id.login_button)).perform(click());
onView(withId(R.id.welcome_text)).check(matches(withText("Welcome!")));
}
- ลอง Run test แล้วสังเกตดูสิ่งที่เกิดขึ้น