简体   繁体   English

如何在Robolectric中对RecyclerView,LinearLayoutManager进行单元测试?

[英]How do I unit test RecyclerView , LinearLayoutManager in Robolectric?

How do I unit test RecyclerView, ScrollListener , LinearLayoutManager in Robolectric? 如何在Robolectric中对RecyclerView,ScrollListener,LinearLayoutManager进行单元测试?

Im fairly new to this kind of testing but I really wanted to imitate gestures, especially scrolling. 我是一个相当新的测试,但我真的想模仿手势,特别是滚动。

I guess what you really wan't to test is your code and if it behaves as desired using these components. 我想你真正想要测试的是你的代码,如果它使用这些组件表现得如此。

Since the scope of your question is pretty wide, let me give it a use-case.: 由于你的问题范围很广,让我给它一个用例:

Let's assume you have a fragment with a RecyclerView, which has a LinearLayoutManager. 假设你有一个带有RecyclerView的片段,它有一个LinearLayoutManager。 You want to test if a click on one of the items triggers the right method call on another layer. 您想要测试其中一个项目的单击是否在另一个图层上触发正确的方法调用。 (Let's say you use MVP and that is the presenter) (假设您使用的是MVP,那就是演示者)

A possible test could look like this.: 可能的测试看起来像这样:

@RunWith(RobolectricGradleTestRunner::class)
@Config(constants = BuildConfig::class, sdk = intArrayOf(21))
class MyFragmentTest {

lateinit var fragment: MyFragment
lateinit var activityController: ActivityController<FragmentActivity>

@Before
@Throws(Exception::class)
fun setUp() {
    fragment = MyFragment()

    activityController = Robolectric.buildActivity(FragmentActivity::class.java)

    activityController.create().start().resume()

    activityController.get()
            .supportFragmentManager
            .beginTransaction()
            .add(fragment, null)
            .commit()
}

@Test
@Throws(Exception::class)
fun testClickEntry() {
    val recycler = fragment.view!!.findViewById(R.id.sideNavigationRecycler) as RecyclerView
    // workaround robolectric recyclerView issue
    recycler.measure(0,0)
    recycler.layout(0,0,100,1000)

    // lets just imply a certain item at position 0 for simplicity
    recycler.findViewHolderForAdapterPosition(0).itemView.performClick()

    // presenter is injected in my case, how this verification happens depends on how you manage your dependencies. 
    verify(fragment.presenter).onEntryClicked(MyNavigationEntry.XYZ)
}
}

Sorry for the syntax first of all, I use Kotlin in my tests. 对不起语法首先,我在测试中使用Kotlin。

I have to say though I'm not 100% happy with this by myself but i think its reasonable if you wan't to test the correct communication of your layers. 我不得不说,虽然我自己并不是100%满意,但我认为如果你不想测试你的图层的正确沟通是合理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM