Skip to content

Instantly share code, notes, and snippets.

@igorokr
Last active October 8, 2022 21:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igorokr/5f3db37f0b9eb8b2feae to your computer and use it in GitHub Desktop.
Save igorokr/5f3db37f0b9eb8b2feae to your computer and use it in GitHub Desktop.
Android Espresso: custom spinner selected item matcher by text. Checks if specific text presents in any TextView (or their heirs) of Spinner selected item.
package com.rirdev.aafl.demo.test.ui;
import android.content.res.Resources;
import android.support.test.espresso.matcher.BoundedMatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Spinner;
import android.widget.TextView;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import static android.support.test.internal.util.Checks.checkNotNull;
import static org.hamcrest.Matchers.is;
/**
* Created by IgorOK on 03.01.2016.
*/
public final class MyCustomViewMatchers {
private static final String TAG = MyCustomViewMatchers.class.getSimpleName();
public static Matcher<View> withTextInSpinnerSelectedView(final Matcher<String> stringMatcher) {
checkNotNull(stringMatcher);
return new BoundedMatcher<View, Spinner>(Spinner.class) {
@Override
public void describeTo(Description description) {
description.appendText("with text In Spinner Selected View: ");
stringMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(Spinner spinner) {
return findTextRecursively(spinner.getSelectedView());
}
private boolean findTextRecursively(View view) {
if (view instanceof ViewGroup) {
ViewGroup innerViewGroup = (ViewGroup)view;
for (int i = 0; i < innerViewGroup.getChildCount(); i++) {
View innerView = innerViewGroup.getChildAt(i);
if (innerView instanceof TextView) {
if (isTextMatch((TextView) innerView)) {
return true;
}
} else if (innerView instanceof ViewGroup) {
return findTextRecursively(innerView);
}
}
} else if (view instanceof TextView) {
return isTextMatch((TextView) view);
}
return false;
}
private boolean isTextMatch(TextView textView) {
String text = textView.getText().toString();
if (stringMatcher.matches(text)) {
String resName = getViewIdName(textView);
Log.d(TAG, String.format("Text '%s' found in view with id '%s'", text, resName)); // LOG not work
return true;
}
return false;
}
private String getViewIdName(View view) {
String resName = "@NULL";
try {
resName = view.getResources().getResourceName(view.getId());
} catch (Resources.NotFoundException e) {
Log.d(TAG, String.format("Resource not found. id -> %s", view)); // LOG not work
}
return resName;
}
};
}
public static Matcher<View> withTextInSpinnerSelectedView(String text) {
return withTextInSpinnerSelectedView(is(text));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment