3
我已經嘗試使用Mockito的測試按鈕功能。該代碼包括佈局/ SampleActivity /單元測試的主要內容:btn.performClick()無法模擬對象,但活動調用函數是能
佈局文件定義:
android:text="testbtnmock"
android:id="@+id/btn_testbtnmock"
android:onClick="testBtnMock"
SampleActivity文件中定義
public void testBtnMock(View view) {
System.out.println("value:"+getInt());
}
public int getInt(){
return 0;
}
單元測試文件中定義
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class SampleActivityTest {
private SampleActivity sampleActivity;
private Button testBtnMock;
@Before
public void setUp() {
ShadowLog.stream = System.out;
}
@Test
public void testBtnMock() {
sampleActivity = Robolectric.setupActivity(SampleActivity.class);
SampleActivity spySampleActivity = spy(sampleActivity);
when(spySampleActivity.getInt()).thenReturn(100);
//spySampleActivity.testBtnMock(mock(View.class)); //it is working , print 100
testBtnMock = (Button) sampleActivity.findViewById(R.id.btn_testbtnmock);
testBtnMock.performClick(); //it is not work , print 0 ,mock invalid
}
}
我的問題是:
- 爲什麼使用
spySampleActivity.testBtnMock(mock(View.class));
觸發的testBtnMock(View v)
功能。它正在工作並打印100. - 但使用
testBtnMock.performClick();
不起作用並打印0.爲什麼?如何解決它?