我正在尝试测试一个使用 viewBinding 来显示视图的片段,以及一个使用 viewModel 来获取该数据的片段。
我想编写一个 UI 测试来查看某些数据是否可见,但是到目前为止我没有运气,我希望有人可以帮助我,因为我对 UI 测试还是很陌生。
到目前为止,我尝试模拟 viewModel、liveData 和 viewBinding,但没有成功
这是我尝试做的一些示例类
我的视图模型:
private val bike: MutableLiveData<Bike> = MutableLiveData()
val getBike: LiveData<BikeType>
get() = bikeType
fun getBike() {
BikeService().getBike(bikeId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
bike.postValue(it)
}, {
Timber.e(it)
}).let { disposeBag.add(it) }
}
}
}
我的片段
class BikeFragment : AppAbstractBaseFragment<Any>(), BikeView,
OnBackPressedListener {
var mBinding: FragmentBikeBinding? = null
var viewModel: BikeViewModel? = null
var cancellable: Boolean = false
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mBinding = FragmentBikeBinding.inflate(inflater, container, false)
return mBinding?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (viewModel == null) {
viewModel = ViewModelProvider(this).get(BikeViewModel::class.java)
}
mBinding?.apply {
this.view = this@BikeDashboardFragment
viewModel?.getBike?.observe(viewLifecycleOwner, { newBike ->
bike = newBike
})
}
viewModel?.getBike()
}
考试
class BikeTest {
@get:Rule
val screenshotTestRule = ScreenshotTestRule()
@Rule
@JvmField
val dataBindingIdlingResourceRule = DataBindingIdlingResourceRule()
@Rule
@JvmField
var instantExecutor = InstantTaskExecutorRule()
private var scenario: FragmentScenario<BikeFragment>? = null
private var bikeData = mockk<MutableLiveData<Bike>>()
private var viewModel = mockk<BikeViewModel>(relaxed = true)
private val lifecycleOwner: LifecycleOwner = mockk()
private var fakeBike =
Bike(id = 1, cancellable = true, linkable = true, ownerName = "Joske")
var context: Context? = null
@Before
fun setUp() {
val app = ApplicationProvider.getApplicationContext<BaseApplication>()
context = app.applicationContext
}
@Test
fun loadBikeSeeTheRightBikeData() {
scenario = launchFragmentInContainer(
themeResId = R.style.Theme_Brand
)
dataBindingIdlingResourceRule.monitorFragment(scenario!!)
scenario?.onFragment {
it.mBinding?.bike = fakeBike
onView(withId(R.id.ownerNameTextView)).check(matches(withText("Klaartje")))
}
}
}