jeudi 17 janvier 2019

Building a NoMatchingViewException while testing Android UI with Espresso

While testing the recyclerView present in my application, I am creating custom RecyclerView assertions and actions to perform Espresso tests on them.

I have a RecyclerView that has 4 children layouts. I need to perform actions and assertions on the children of these layouts. The ViewAssertion I am implementing has to take the position on the recyclerView, the resource id and the assertion that I need to execute on that child.

When overriding the check method I found the view I am interested in, and then called the passed assertion's check method. Here is my problematic NoMatchingViewException since check method looks as follows:
override fun check(view: View?, noViewFoundException: NoMatchingViewException?)

I understand that passing null instead of noViewFoundException indicate that the view hasn't been found.

What I don't like about my code is this try catch block. If I understand the NoMatchingViewException correctly, it should be created when the item you want the assertion to be executed on is not found. If I get things wrong, please tell me that.

Calling the method.

val childView: View?
return try {
    childView = itemAtPosition.findViewById(viewId)
    viewAssertion.check(
        childView, null
    )
} catch (e: Exception) {
    viewAssertion.check(null, 
    ExceptionBuilderHelper.buildNoMatchingViewException(recyclerView, viewId))
}

And the method buildNoMatchingViewException:

fun buildNoMatchingViewException(rootView: View, searchedViewId: Int) : NoMatchingViewException {
    return  NoMatchingViewException.Builder()
        .withRootView(rootView)
        .withViewMatcher(ViewMatchers.withId(searchedViewId))
        //TODO: fix the list of nulls...
        .withAdapterViews(listOf(null))
        .withAdapterViewWarning(EspressoOptional.absent())
        .withCause(java.lang.IllegalStateException("No view in recyclerView of id: " + rootView.id + " with id: " + searchedViewId))
        .build()
}

As in the TODO, I do not want to create a listOf(null) since it is more than stupid. How do I correctly build up this exception? If this code is the way, what should be passed in the builder methods - especially withAdapterViews.

Aucun commentaire:

Enregistrer un commentaire