简体   繁体   English

编写片段的单元测试

[英]Writing Unit Tests for Fragment

I have the following data class which holds the resource id and the onClickListener for a view: 我有以下数据类,其中包含资源ID和视图的onClickListener:

data class Item(val name: Int, val onClick: View.OnClickListener)

Later I populate a Layouts children with ( children extends ViewGroup to get a list of child views): 稍后,我用填充Layouts子项( children扩展了ViewGroup以获得子视图的列表):

fun loadItems(list: List<Item>, viewGroup: ViewGroup){
    viewGroup.children.zip(list) { view, item ->
        (view as TextView).text = resources.getString(item.name)
        view.setOnClickListener(item.onClick)
    }
}

I want to test if a child of the ViewGroup 我想测试ViewGroup的孩子

  • Has the String of the resource I provided in the item 具有我在项目中提供的资源的字符串
  • Has the listener I provided in the item 在项目中提供了我提供的收听者

This code is part of a fragment. 此代码是片段的一部分。 What is the easiest way to do this? 最简单的方法是什么? I want this to be a local test. 我希望这是本地测试。

Your best bet for a local test that involves some Android components as Activities or Fragments would be to use Robolectric as it performs tests using the JVM. 对于涉及一些Android组件(例如“活动”或“片段”)的本地测试,最好的选择是在使用JVM执行测试时使用Robolectric。

That being said, however, I assume that you're dealing with testing a list and the content of its items. 话虽这么说,但是我认为您正在测试列表及其项目的内容。 In this case, you would probably be better off using Espresso particularly with its onData() calls. 在这种情况下,最好使用Espresso,尤其是对其onData()调用。 Worthy of note is that for such UI-related tests, you will need a device or emulator. 值得注意的是,对于此类与UI相关的测试,您将需要设备或仿真器。

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

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