Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check Toolbar title in android instrumental test?

I found great instrumental test tutorial on YT Advanced Android Espresso. I took code from there with small adjustment to my needs.

import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withChild;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.core.AllOf.allOf;

...

@Test
public void checkToolbarTitle() {
    String toolbarTitile = getInstrumentation().getTargetContext().getString(R.string.my_bus_stops);
    onView(allOf(isAssignableFrom(TextView.class), withParent(isAssignableFrom(Toolbar.class)))).check(matches(withText(toolbarTitile)));
}

Unfortunatelly it does not work for me. Test failed with:

android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: (is assignable from class: class android.widget.TextView and has parent matching: is assignable from class: class android.widget.Toolbar)

What is wrong with it? How can I test it in other way?

like image 748
Grzegorz Bielański Avatar asked Mar 31 '16 09:03

Grzegorz Bielański


2 Answers

This works for me:

onView(allOf(instanceOf(TextView.class), withParent(withId(R.id.toolbar))))
    .check(matches(withText("toolbarTitile")));
like image 53
denys Avatar answered Sep 23 '22 05:09

denys


SOLUTION

The method is fine. As Chiu-Ki Chan wrote in her tutorial you can "pinpoint that one particular view". BUT you have to make sure you imported proper Toolbar:

import  android.support.v7.widget.Toolbar;

instead of:

import android.widget.Toolbar;
like image 41
Grzegorz Bielański Avatar answered Sep 20 '22 05:09

Grzegorz Bielański