Android RecyclerView Test하기

James_·2022년 5월 22일
0

RecyclerView Test를 하면서 기본적으로 테스트하기 어렵다는 생각이 들었다.

androidTest 폴더를 만들고 테스트 클래스를 만든 다음 보일러플레이트 코드를 복사해주자

    fun nthChildOf(parentMatcher: Matcher<View>, childPosition: Int): Matcher<View> {
        return object : TypeSafeMatcher<View>() {
            override fun describeTo(description: Description) {
                description.appendText("position $childPosition of parent ")
                parentMatcher.describeTo(description)
            }

            public override fun matchesSafely(view: View): Boolean {
                if (view.parent !is ViewGroup) return false
                val parent = view.parent as ViewGroup

                return (parentMatcher.matches(parent)
                        && parent.childCount > childPosition
                        && parent.getChildAt(childPosition) == view)
            }
        }
    }

해당 메서드는 N번째 Child를 View로 리턴해주는 함수다.

    @RunWith(JUnit4::class)
class PlayListFeature {

    val mActivityRule = ActivityTestRule(MainActivity::class.java)
        @Rule get
    
    @Test
    fun displaysListOfPlayLists(){
        Thread.sleep(4000L)

		// R.id.playlists -> RecyclerView Id
        assertRecyclerViewItemCount(R.id.playlists_list,10)
        // isDescendantOfA 지정된 상위 유형을 기준으로 뷰와 일치하는 일치자를 반환합니다.
        // RecyclerView Item layout, R.id.playlist_name,R.id.playlist_category, image
        onView(allOf(withId(R.id.playlist_name), isDescendantOfA(nthChildOf(withId(R.id.playlists_list),0))))
            .check(matches(withText("Hard Rock Cafe")))
            .check(matches(isDisplayed()))

        onView(allOf(withId(R.id.playlist_category), isDescendantOfA(nthChildOf(withId(R.id.playlists_list),0))))
            .check(matches(withText("rock")))
            .check(matches(isDisplayed()))

        onView(allOf(withId(R.id.playlist_image), isDescendantOfA(nthChildOf(withId(R.id.playlists_list),0))))
            .check(matches(withDrawable(R.mipmap.playlist)))
            .check(matches(isDisplayed()))
    }
    
}

그리고 해당 모듈들을 Import하기 헷갈릴 수 있으니 import문을 참고해서 import를 추천한다.
modules

import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.rule.ActivityTestRule
import com.schibsted.spain.barista.assertion.BaristaRecyclerViewAssertions.assertRecyclerViewItemCount
import com.schibsted.spain.barista.internal.matcher.DrawableMatcher.Companion.withDrawable
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
profile
Android 개발자

0개의 댓글