Android UI Test with WebView

Android UI Test

These days, Espresso covers a lot of UI Test features.
And Espresso covers WebView contents assertion with espresso-web.

It’s nice to test WebView base application.
In this entry, I want to explain


Before staring, we add some dependencies for espresso and espresso web

android {
    defaultConfig {
        testInstrumentationRunner ""
    packagingOptions {
        exclude 'META-INF/maven/'
        exclude 'META-INF/maven/'

I added testInstrumentationRunner and packagingOptions.
testInstrumentationRunner is for UnitTest annotation.
packagingOptions is to solve build problem.

dependencies {
  compile ''
  androidTestCompile ''
  androidTestCompile ''
  androidTestCompile ''
  androidTestCompile ''

I added above libraries

Now you can resolve dependencies to start Test.

UI Test

Espresso : Google Developer

There are a lot of test methods

WebView Test

Espresso Web covers WebView based application test. You can detect DOM using API.
Documentation : Espresso Web

We can get WebView controller and verify by DOM.


This example tests small web service.
Press button and open WebView and check contents (This is virtual test and it doesn’t work as it is).

This class is helper to wait until button becomes enables.
In this example, button becomes when the service is ready.

public ButtonIdlingResource implements IdlingResource {
  private ResourceCallback resourceCallback;
  private Button button;

  public PortalButtonIdlingResource(PortalButton button) {
    this.button = button;

  public String getName() {
      return ButtonIdlingResource.class.getName();

  public boolean isIdleNow() {
      boolean idle = this.button.isEnabled();
      if (idle && resourceCallback != null) {
      return idle;

  public void registerIdleTransitionCallback(ResourceCallback callback) {
      this.resourceCallback = callback;

Test code(
Steps of this code.

public class EspressoTest {

    private Activity activity;

    public ActivityTestRule<MainActivity> activityTestRule = new ActivityTestRule(MainActivity.class);

    public void setUp(){
        this.activity = activityTestRule.getActivity();

    public void serviceTest() {
         Button button = (Button)activity.findViewById(;   // Retrieve Button from layout

         // Wait until the target button becomes enable
         IdlingResource idlingResource = new PortalButtonIdlingResource(button);

         // Find button and click(you have several choices to find UI from Activity)

         // If you can click button, new activity is displayed and webview will start loading.
          Web.onWebView().check(WebViewAssertions.webContent(DomMatchers.containingTextInBody("Android")));   // Check WebView body

Now, ready to start test.
The way of running is same as app.

WebView.onWebView().check waits until page is loaded.