【问题标题】:Possible to mock/test Android ViewBinding interactions?可以模拟/测试 Android ViewBinding 交互吗?
【发布时间】:2020-04-01 07:52:33
【问题描述】:

目前正在尝试在单元测试中测试与 ViewBinding 类的交互

"Invalid Input" should {
    "disable the LoginButton" {
        val viewBinding: FrLoginBinding = mockk()

        InvalidInputViewStateBinder.bind(InvalidInput, viewBinding)

        verify { viewBinding.loginButton.isEnabled = false }
    }
}

这就是我的想法。 ViewBinding 中的视图是公共的最终属性,不能轻易模拟。至少我做不到。传递 View 模拟来创建 ViewBinding 也不起作用,因为我必须为此模拟 findViewById

有没有人试过这个并让它工作?

【问题讨论】:

  • 您找到解决方法了吗?
  • 还没有,很快会做更多的挖掘
  • @mochadwi,我添加了一个实现细节,说明您需要如何在下面模拟部分模拟视图绑定。但是您需要先访问模拟的视图绑定,然后才能对其进行验证。

标签: android unit-testing android-viewbinding


【解决方案1】:

我遇到了同样的问题。这是我的解决方法


@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() 接口方法以将根设置为模拟的根视图。

【讨论】:

  • 所以对于 LayoutBinding 的每个视图,我需要提供一个模拟并使用 Whitebox 设置内部状态?即使对它们没有断言?
  • @FloWe 您应该可以模拟特定视图并使用白框进行设置。
猜你喜欢
  • 2011-01-06
  • 2011-08-03
  • 2017-09-16
  • 1970-01-01
  • 2018-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-11
相关资源
最近更新 更多