我用mockito有try test按钮功能。代码包括layout/sampleactivity/unittest主要内容:
布局文件定义:

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;
}

unittest文件定义
@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。为什么?怎么解决?

最佳答案

这很容易解释。
xml属性将用于通过反射调用方法(How does the android Xml attribute android:onClick="..." work behind the scenes?)。
因此,经过一些简化,将使用来自按钮的上下文,反射将调用方法。Button在膨胀期间获取上下文,它是非间谍活动的引用。这就是为什么在测试中调用真正的方法。
当您通过对间谍活动的引用调用该方法时,它会工作。
如何修复:
提取负责提供整数的类
模拟注射试验
类似于:

public class IntegerProvider {
  public int getInt(){
     return 0;
  }
}

public class SampleActivity {
   IntegerProvider intProvider;

   public void testBtnMock(View view) {
     System.out.println("value:" + intProvider.getInt());
   }
}

@Test
public void testBtnMock() {
    sampleActivity = Robolectric.setupActivity(SampleActivity.class);
    IntegerProvider providerMock = mock(IntegerProvider.class);
    when(providerMock.getInt()).thenReturn(100);
    sampleActivity.intProvider = providerMock;

    testBtnMock = (Button) sampleActivity.findViewById(R.id.btn_testbtnmock);
    testBtnMock.performClick();
}

10-06 03:25