Created
October 15, 2017 15:54
-
-
Save txusballesteros/eed78bd057ddb9d5353bd96e76d8c799 to your computer and use it in GitHub Desktop.
Espresso RecyclerView Assertions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.txusballesteros.instrumentacion.assertion | |
import android.support.test.espresso.EspressoException | |
import android.support.test.espresso.ViewAssertion | |
import android.support.test.espresso.matcher.ViewMatchers.assertThat | |
import android.support.v7.widget.RecyclerView | |
import android.view.View | |
import android.view.View.FIND_VIEWS_WITH_TEXT | |
import android.widget.TextView | |
import org.hamcrest.Matchers.greaterThan | |
import org.junit.Assert.assertEquals | |
import org.junit.Assert.assertFalse | |
fun hasItems() = ViewAssertion { view, noViewFoundException -> | |
if (view is RecyclerView) { | |
assertThat(view.adapter.itemCount, greaterThan(0)) | |
} else { | |
throw noViewFoundException | |
} | |
} | |
fun hasViewWithTextAtPosition(position: Int = 0, | |
expectedValue: CharSequence) = ViewAssertion { view ,_ -> | |
if (view is RecyclerView) { | |
val outViews = arrayListOf<View>() | |
view.findViewHolderForAdapterPosition(position).itemView | |
.findViewsWithText(outViews, expectedValue, FIND_VIEWS_WITH_TEXT) | |
assertFalse(outViews.isEmpty()) | |
} else { | |
throw RecyclerViewAssertionException("The view is not a RecyclerView.") | |
} | |
} | |
inline fun hasViewWithIdAtPosition(position: Int = 0, | |
viewId: Int, | |
crossinline assert: (View) -> Unit) = ViewAssertion { view ,_ -> | |
if (view is RecyclerView) { | |
view.findViewHolderForAdapterPosition(position).itemView.findViewById<View>(viewId)?.let { | |
assert(it) | |
} ?: throw RecyclerViewAssertionException("The view holder hasn't got a view with the specified ID, $viewId.") | |
} else { | |
throw RecyclerViewAssertionException("The view is not a RecyclerView.") | |
} | |
} | |
fun hasViewWithIdAndTextAtPosition(position: Int = 0, | |
viewId: Int, | |
expectedValue: CharSequence) = ViewAssertion { view ,_ -> | |
if (view is RecyclerView) { | |
view.findViewHolderForAdapterPosition(position).itemView.findViewById<TextView>(viewId)?.let { | |
assertEquals(expectedValue, it.text) | |
} ?: throw RecyclerViewAssertionException("The view holder hasn't got a view with the specified ID, $viewId.") | |
} else { | |
throw RecyclerViewAssertionException("The view is not a RecyclerView.") | |
} | |
} | |
class RecyclerViewAssertionException(message: String): RuntimeException(message), EspressoException |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment