如何使用Mockito Kotlin片段/活动来模拟kotlinx.android.synthetic的意见

我有一个在Kotlin写的片段。 我使用导入布局视图

导入kotlinx.android.synthetic.main.my_fragment_layout。*

在我的Fragment类中的一个方法中,我在布局中为TextView设置文本。 例如:

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

在我的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"); } 

当我在Kotlin中编写片段时,如何执行类似的实现,并使用以下导入视图: import kotlinx.android.synthetic.main.my_fragment_layout。

我认为Robolectric是这种类型的测试更合适的工具。 使用它你可以有一个更简单的方法来在JVM上测试Android依赖的代码。

例如,你测试看起来像这样:

 @Test fun `should set hello`() { val fragment = YourFragment() fragment.setViews() assertEquals(fragment.myTextView.getText().toString(), "Hello"); }