콘텐츠로 건너뛰기

자주 방문한 페이지

최근 방문한 페이지

navigation

Espresso Web

Espresso-Web is an entry point to work with Android WebView UI components. Espresso-Web reuses Atoms from the popular WebDriver API to examine and control the behavior of a WebView.

When to use Espresso-Web

Use Espresso-Web to test your hybrid apps, especially the integration of your app’s native UI components with its WebView UI components. You can use the Espresso-Web API in conjunction with other Espresso APIs to fully interact with web elements inside WebView objects.

If you need to test only the WebView itself, and not the interactions between the WebView and native components in your app, consider writing a general web test using a framework like WebDriver. If you use a web testing framework, you don’t need to use an Android device or a Java Virtual Machine, which makes your tests run more quickly and reliably. That being said, Espresso-Web allows you to reuse your custom WebDriver atoms, which gives you a lot of flexibility, especially when writing tests that you plan to run against both standalone web apps and apps that include an Android UI.

How it works

Similarly to Espresso’s onData() method, a WebView interaction comprises several Atoms. WebView interactions use a combination of the Java programming language and a JavaScript bridge to do their work. Because there is no chance of introducing race conditions by exposing data from the JavaScript environment—everything Espresso sees on the Java-based side is an isolated copy—returning data from Web.WebInteraction objects is fully supported, allowing you to verify all data that’s returned from a request.

What is a WebDriver Atom?

The WebDriver framework uses Atoms to find and manipulate web elements programmatically. Atoms are used by WebDriver to allow browser manipulation. An Atom is conceptually similar to a ViewAction, a self-contained unit that performs an action in your UI. You expose Atoms using a list of defined methods, such as findElement() and getElement(), to drive the browser from the user’s point of view. However, if you use the WebDriver framework directly, Atoms need to be properly orchestrated, requiring logic that is quite verbose.

Within Espresso, the classes Web and Web.WebInteraction wrap this boilerplate and give an Espresso-like feel to interacting with WebView objects. So in a context of a WebView, Atoms are used as a substitution to traditional Espresso ViewMatchers and ViewActions.

The API then looks quite simple:

onWebView()
    .withElement(Atom)
    .perform(Atom)
    .check(WebAssertion);

To learn more, read Selenium’s documentation on Atoms.

Implementing WebView

Packages

To include Espresso-Web in your project, complete the following steps:

  1. Open your app’s build.gradle file. This is usually not the top-level build.gradle file but app/build.gradle.
  2. Add the following line inside dependencies:

    androidTestCompile 'com.android.support.test.espresso:espresso-web:3.0.1'
    
  3. Espresso-Web is only compatible with Espresso 2.2 or higher and the Android Testing Support Library 0.3 or higher, so make sure you update those lines as well:

    androidTestCompile 'com.android.support.test:runner:1.0.1'
    androidTestCompile 'com.android.support.test:rules:1.0.1'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:3.0.1'
    

Common API usage

The onWebView() method is the main entry point when working with WebView on Android using Espresso. You use this method to perform Espresso-Web tests, such as the following:

onWebView()
    .withElement(findElement(Locator.ID, "link_2")) // similar to onView(withId(...))
    .perform(webClick()) // Similar to perform(click())

    // Similar to check(matches(...))
    .check(webMatches(getCurrentUrl(), containsString("navigation_2.html")));

In this example, Espresso-Web locates a DOM element whose ID is "link_2" and clicks on it. The tool then verifies that the WebView sends a GET request containing the "navigation_2.html" string.

Note: When executing your tests, the system performs all WebView interactions using JavaScript. Therefore, to support JavaScript evaluation, the WebView under test must have JavaScript enabled.

You can force JavaScript to be enabled by overriding afterActivityLaunched() in the ActivityTestRule and calling onWebView().forceJavascriptEnabled(). Enabling JavaScript may cause the WebView under test to be reloaded. This is necessary to ensure that AndroidJUnitRunner loads all needed test infrastructure, including JavaScript interactions:

@Rule
public ActivityTestRule mActivityRule =
        new ActivityTestRule(WebViewActivity.class,
        false, false) {
    @Override
    protected void afterActivityLaunched() {
        onWebView().forceJavascriptEnabled();
    }
}

Common web interactions

Common interactions with Web.WebInteraction objects include the following:

Example

The following example tests whether, after entering text into a WebView and selecting a Submit button, the same text appears within a different element in the same WebView:

public static final String MACCHIATO = "Macchiato";

@Test
public void typeTextInInput_clickButton_SubmitsForm() {
    // Lazily launch the Activity with a custom start Intent per test.
    mActivityRule.launchActivity(withWebFormIntent());

    // Selects the WebView in your layout. If you have multiple WebView objects,
    // you can also use a matcher to select a given WebView,
    // onWebView(withId(R.id.web_view)).
    onWebView()
        // Find the input element by ID.
        .withElement(findElement(Locator.ID, "text_input"))

        // Clear previous input and enter new text into the input element.
        .perform(clearElement())
        .perform(DriverAtoms.webKeys(MACCHIATO))

        // Find the "Submit" button and simulate a click using JavaScript.
        .withElement(findElement(Locator.ID, "submitBtn"))
        .perform(webClick())

        // Find the response element by ID, and verify that it contains the
        // entered text.
        .withElement(findElement(Locator.ID, "response"))
        .check(webMatches(getText(), containsString(MACCHIATO)));
}

See also the Espresso Web sample on GitHub.

이 사이트는 쿠키를 사용하여 사이트별 언어 및 표시 옵션에 대한 환경설정을 저장합니다.

Google Play에서 성공을 거두는 데 도움이 되는 최신 Android 개발자 뉴스 및 도움말을 받아 보세요.

* 필수 입력란

완료되었습니다.

WeChat에서 Google Developers 팔로우하기

이 사이트를 (으)로 탐색할까요?

페이지를 요청했지만 이 사이트의 언어 환경설정은 입니다.

언어 환경설정을 변경하고 이 사이트를 (으)로 탐색할까요? 언어 환경설정을 나중에 변경하려면 각 페이지 하단의 언어 메뉴를 사용하세요.

이 클래스를 사용하려면 API 수준 이상이 필요합니다.

문서에 대해 선택한 API 수준이 이므로 이 문서가 표시되지 않습니다. 왼쪽 탐색 메뉴의 선택기로 문서 API 수준을 변경할 수 있습니다.

앱에 필요한 API 수준 지정에 관한 자세한 내용은 다양한 플랫폼 버전 지원을 참조하세요.

Take a short survey?
Help us improve the Android developer experience. (April 2018 — Developer Survey)