小编Ash*_*Jha的帖子

如何在Android中模拟Kotlin的kotlinx.android.synthetic视图

我有一个用科特林写的片段。我使用导入布局视图

import kotlinx.android.synthetic.main.my_fragment_layout.
Run Code Online (Sandbox Code Playgroud)

在我的一种方法中,我设置了TextView的文本:

fun setViews() {
    myTextView.text = "Hello"
    // In Java I would have used:
    // (getView().findViewById(R.id.myTextView)).setText("Hello");
}
Run Code Online (Sandbox Code Playgroud)

在普通的JVM单元测试中,我想使用Mockito测试此方法。例如,如果上述方法是用Java编写的,则可以执行以下操作:

public void setViewsTest() {
    // Mock dependencies
    View view = Mockito.mock(View.class);
    TextView myTextView = Mockito.mock(TextView.class);
    when(fragment.getView()).thenReturn(view);
    when(view.findViewById(R.id. myTextView)).thenReturn(myTextView);

    // Call method
    fragment.setViews();

   // Verify the test
   verify(myTextView).setText("Hello");
}
Run Code Online (Sandbox Code Playgroud)

使用Kotlin的kotlinx.android.synthetic视图时如何做类似的实现?

android unit-testing mockito kotlin android-testing

5
推荐指数
1
解决办法
1167
查看次数

标签 统计

android ×1

android-testing ×1

kotlin ×1

mockito ×1

unit-testing ×1