Issue
Here Kotlin’s snippet:
fun withBackgroundColorResId(@IdRes expectedId: Int): Matcher<Any> {
return object : BoundedMatcher<Any, Any>(Any::class.java) {
override fun matchesSafely(view: Any): Boolean {
if (view !is View || view !is ViewGroup) {
Log.w(TAG, "withBackgroundColorResId_incorrect_type, view $view")
return false
}
val currenColor (view.background.current as ColorDrawable).color
val expectedColor ContextCompat.getColor(view.context, expectedId)
return currenColor expectedColor
}
override fun describeTo(description: Description) {
description.appendText("textView with background color resId: ")
description.appendValue(context.getResources().getString(expectedId))
}
}
}
and usage:
onView(withRecyclerView(tradersRecyclerView).atPositionOnView(traderCheckPos, pauseTextView)).check(matches(withBackgroundColorResId(trade_not_running_color)))
and here logcat:
06-05 10:25:12.787 I/ViewInteraction(22053): Checking 'MatchesViewAssertion{viewMatchertextView with background color resId: "#ffbde6ff"}' assertion on view RecyclerView with id: com.myproject.debug:id/tradersRecyclerView at position: 0
06-05 10:25:12.787 W/com.myproject.custom.matcher.CustomMatchers(22053): withBackgroundColorResId_incorrect_type, view androidx.appcompat.widget.AppCompatTextView{a412c35 V.ED..C.. ........ 0,0-288,288 #7f0800c9 app:id/pauseTextView}
06-05 10:25:12.794 D/com.myproject.activity.TradersActivityTest(22053): afterEach
06-05 10:25:12.794 I/MockWebServer(22053): MockWebServer[8081] done accepting connections: Socket closed
06-05 10:25:12.825 D/LifecycleMonitor(22053): Lifecycle status change: com.myproject.ui.activity.TradersActivity@2964795 in: PAUSED
06-05 10:25:12.825 D/LifecycleMonitor(22053): running callback: androidx.test.rule.ActivityTestRule$LifecycleCallback@9705558
06-05 10:25:12.825 D/LifecycleMonitor(22053): callback completes: androidx.test.rule.ActivityTestRule$LifecycleCallback@9705558
as you can see the object “view” has type androidx.appcompat.widget.AppCompatTextView
. As we known AppCompatTextView
is extends from View
But why it print
withBackgroundColorResId_incorrect_type, view androidx.appcompat.widget.AppCompatTextView
?
Solution
In Kotlin’s documentation is
states:
checks that a value has a certain type
So according to Your code, You ask in a way
is my view instance of X?
Following this line You get:
- is
view instanceof View
? Answer is yes. - is
view instanceof ViewGroup
? Answer is no.
Single views extends mainly by View class. ViewGroups are mostly used in more complex layouts like LinearLayout
,FrameLayout
, etc.
Concluding the results, You have:
true||false
true
Answered By – deadfish