可以模拟/测试 Android ViewBinding 交互吗? [英] Possible to mock/test Android ViewBinding interactions?

查看:51
本文介绍了可以模拟/测试 Android ViewBinding 交互吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

currently trying to test the interactions with ViewBinding classes in Unit Tests

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

        InvalidInputViewStateBinder.bind(InvalidInput, viewBinding)

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

这样的事情是我想到的.ViewBinding 中的视图是公共最终属性,不能轻易模拟.至少我做不到.传递一个 View 模拟来创建 ViewBinding 也不起作用,因为我必须为它模拟 findViewById.

something like this is what i had in mind. The Views in the ViewBinding are public final Properties and cannot easily be mocked. At least i'm unable to. Passing a View mock to create the ViewBinding also doesn't work, as i'd have to mock findViewById for it.

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

Has anyone tried this out and got it to work?

推荐答案

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

I came across this same issue. Here is how I resolved it


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

Use Whitebox to set the properties (i.e. the views by id) and mock the getRoot() interface method to set the root to your mocked root view.

这篇关于可以模拟/测试 Android ViewBinding 交互吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆