在我的ViewModel中,我会得到下一个乐趣:
fun onTitleClick(titleName: Int) {
when (titleName) {
R.string.about_terms_service -> {
termsOfServiceItemClickEvent.postValue(
ViewModelEvent(
WebViewFragment.newBundle(
url = TERMS_LINK,
title = "Terms of Service"
)
)
)
}
R.string.about_open_source_licenses -> licenseItemClickEvent.postValue(ViewModelEvent(R.string.about_open_source_licenses))
}
}
并具有下一个Event类:
open class ViewModelEvent<out T>(private val content: T? = null) {
var hasBeenHandled = false
private set
/**
* Returns the content and prevents its use again.
*/
fun getContentIfNotHandled(): T? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
}
/**
* Returns the content, even if it's already been handled.
*/
fun peekContent(): T? = content
}
在事件类中,我接下来有一些逻辑fun getContentIfNotHandled()
。我怎样才能在Robolectric测试中测试这种逻辑?
这也是我的片段中的一些代码:
viewModel.licenseItemClickEvent.observe(this, Observer<ViewModelEvent<Int>> {
it?.getContentIfNotHandled()?.let { activity?.addFragment(LicensesFragment()) }
})
答案 0 :(得分:0)
解决下一个解决方案:
@RunWith(RobolectricTestRunner::class)
class ViewModelEventTest {
@Test
@Throws(Exception::class)
fun getContentIfNotHandledTest() {
val viewModelEvent = ViewModelEvent(5)
assertFalse(viewModelEvent.hasBeenHandled)
assertEquals(5, viewModelEvent.getContentIfNotHandled())
assertTrue(viewModelEvent.hasBeenHandled)
assertNull(viewModelEvent.getContentIfNotHandled())
}
}