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

Ash*_*Jha 5 android unit-testing mockito kotlin android-testing

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

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视图时如何做类似的实现?

and*_*cev 2

我认为Robolectric是更适合此类测试的工具。使用它,您可以更轻松地测试 Android 依赖 JVM 的代码。

例如,您的测试将如下所示:

@Test
fun `should set hello`() {
    val fragment = YourFragment()

    fragment.setViews()

    assertEquals(fragment.myTextView.getText().toString(), "Hello");
}
Run Code Online (Sandbox Code Playgroud)