Skip to content

Instantly share code, notes, and snippets.

@tir38
Last active March 25, 2021 06:37
Show Gist options
  • Save tir38/2932eeb55b8fa5347fd5712bff140df0 to your computer and use it in GitHub Desktop.
Save tir38/2932eeb55b8fa5347fd5712bff140df0 to your computer and use it in GitHub Desktop.
Espresso (Hamcrest) matcher to match TextView text but ignoreCase

Let's say you have this code:

textview.setText("This Is Camel Case");

And you want to interact with it in an Espresso test:

import static android.support.test.espresso.matcher.ViewMatchers.withText;

onView(withText("this is camel case"))
  .check(matches(isDisplayed()));

This view would fail the matcher because of the capital letters. But using this matcher will be fine:

import static com.example.app.IgnoreCaseTextMatcher.withText;

onView(withText("this is camel case"))
  .check(matches(isDisplayed()));
package com.example.app;
import android.support.test.espresso.matcher.BoundedMatcher;
import android.view.View;
import android.widget.TextView;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.hamcrest.Matchers.is;
public class IgnoreCaseTextMatcher {
/**
* Returns a matcher that matches {@link TextView} based on its text property value BUT IGNORES CASE.
* Note: View's Sugar for withText(is("string")).
*
* @param text {@link String} with the text to match
*/
public static Matcher<View> withText(String text) {
return withText(is(text.toLowerCase()));
}
private static Matcher<View> withText(final Matcher<String> stringMatcher) {
checkNotNull(stringMatcher);
return new BoundedMatcher<View, TextView>(TextView.class) {
@Override
public void describeTo(Description description) {
description.appendText("with text (ignoring case): ");
stringMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(TextView textView) {
return stringMatcher.matches(textView.getText().toString().toLowerCase());
}
};
}
}
@gnumilanix
Copy link

Or simply do this:

import static org.hamcrest.Matchers.equalToIgnoringCase;

onView( withText(equalToIgnoringCase("HeLLo WoRlD"))
     .check(matches(isDisplayed()))

@alankarjain05
Copy link

alankarjain05 commented Mar 25, 2021

what about situation when you are getting string from resource?

onView(withText(R.string.kb_change_maturity_details_cc))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment