Open GoogleCodeExporter opened 9 years ago
Here's how you can do it: First we create custom matcher
public static Matcher<Object> withCollapsibleToolbarTitle(final Matcher<String> textMatcher) {
return new BoundedMatcher<Object, CollapsingToolbarLayout>(CollapsingToolbarLayout.class) {
@Override
public void describeTo(Description description) {
description.appendText("with toolbar title: ");
textMatcher.describeTo(description);
}
@Override
protected boolean matchesSafely(CollapsingToolbarLayout toolbarLayout) {
return textMatcher.matches(toolbarLayout.getTitle());
}
};
}
Then we match it:
onView(isAssignableFrom(CollapsingToolbarLayout.class)).
check(matches(withCollapsibleToolbarTitle(is(getString(R.string.message_hello)))));
Is there any update on this issue? I used @gnumilanix solution btw and worked perfectly but it's not the most straight forward way to do it and it's still a workaround
Stumbled upon this after a while, basically yeah, what @gnumilanix gave is right. I wouldn't say it's a workaround though, but rather that it's just a new/custom view that doesn't have Matcher support yet. Anyway, I converted that to Kotlin and cleaned it up a bit:
object CustomMatchers {
fun withCollapsingToolbarTitle(@StringRes titleId: Int) =
object : TypedBoundedMatcher<Any, CollapsingToolbarLayout>(CollapsingToolbarLayout::class) {
// used for descriptions
private lateinit var context: Context
private lateinit var titleText: String
private lateinit var titleResName: String
override fun matchesSafely(view: CollapsingToolbarLayout): Boolean {
context = view.context
titleText = context.getString(titleId)
titleResName = context.resources.getResourceName(titleId)
return view.title == titleText
}
override fun describeTo(description: Description?) = description.use {
appendText("with collapsing toolbar title ID: ")
appendValue(titleId)
}
override fun describeMismatchTyped(item: CollapsingToolbarLayout, description: Description) = description.use {
appendText("with collapsing toolbar title ID: ")
appendValue(titleResName)
appendText("resolved as: ")
appendValue(titleText)
appendText("and actual title: ")
appendValue(item.title)
}
}
}
// Adds type safety to describe callbacks
abstract class TypedBoundedMatcher<T : Any, S : T>(
private val expectedType: KClass<out S>
) : BoundedMatcher<T, S>(expectedType.java) {
@Suppress("UNCHECKED_CAST")
override fun describeMismatch(item: Any?, description: Description) = when {
item == null || !expectedType.java.isInstance(item) -> super.describeMismatch(item, description)
else -> describeMismatchTyped(item as S, description)
}
abstract fun describeMismatchTyped(item: S, description: Description)
}
fun Description?.use(block: Description.() -> Any?) = this?.let(block)?.let { Unit } ?: Unit
Ofc you can go with the type-unsafe bounded matcher, but.. Kotlin is so type-safe with awesome type inference, so I'll use it.
Original issue reported on code.google.com by
jacoboak...@gmail.com
on 19 Aug 2015 at 12:48