2016-12-29 33 views
4

我正在使用Espresso爲我的Android應用程序編寫UI測試,並且想要使用MockWebServer模擬http請求。 我需要模擬身份驗證響應並在運行測試之前登錄用戶。模擬服務器請求Android Espresso UI測試

有沒有辦法讓應用程序使用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("[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()); 
} 

回答

3

用匕首更換依賴This example。但是你可以使用任何其他方法來進行DI。主要思想 - 通過自定義測試運行器爲應用程序提供「測試」版本,從而取代測試期間的依賴關係。

相關問題