目前正在尝试在单元测试中测试与ViewBinding类的交互
"Invalid Input" should {
"disable the LoginButton" {
val viewBinding: FrLoginBinding = mockk()
InvalidInputViewStateBinder.bind(InvalidInput, viewBinding)
verify { viewBinding.loginButton.isEnabled = false }
}
}像这样的东西就是我的想法。ViewBinding中的视图是公共的最终属性,不容易被模仿。至少我不能。传递View模拟来创建ViewBinding也不起作用,因为我必须为此模拟findViewById。
有没有人试过这个方法并让它起作用?
发布于 2020-06-24 03:15:49
我也遇到了同样的问题。下面是我解决这个问题的方法
@RunWith(PowerMockRunner::class)
@PrepareForTest(MyLayoutBinding::class)
class MyTestClass {
@Mock
lateinit var mMockViewBinding: MyLayoutBinding
@Mock
lateinit var mMockView: View
@Mock
lateinit var mMockTitleTv: TextView
@Mock
lateinit var mMockRootView: ConstraintLayout
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
PowerMockito.mockStatic(MyLayoutBinding::class.java)
whenever(MyLayoutBinding.bind(mMockView)).thenReturn(mMockViewBinding)
// Use Whitebox for each view component in the layout.
Whitebox.setInternalState(mMockBinding, "title", mMockTitleTv)
// Because 'getRoot' is part of the ViewBinding interface, we just mock the method.
whenever(mMockBinding.root).thenReturn(mMockRootView)
}
}使用Whitebox设置属性(即按id设置视图),并模拟getRoot()接口方法以设置模拟根视图的根。
https://stackoverflow.com/questions/60965983
复制相似问题