我一直在尝试使用 Mockito 测试示例应用程序。
我的测试用例:
public class CalcActivityTest extends ActivityUnitTestCase<CalcActivity> {
private Intent in;
private Button btnAdd,btnSub,btnMul,btnDiv,btnDef;
private TextView res;
private CalcActivity mActivity;
@Mock
private Vars mockVar;
public CalcActivityTest() {
super(CalcActivity.class);
}
@Before
protected void setUp() throws Exception{
super.setUp();
MockitoAnnotations.initMocks(this);
when(mockVar.getn1()).thenReturn(20.0);
when(mockVar.getn2()).thenReturn(40.0);
in = new Intent(getInstrumentation().getTargetContext(),CalcActivity.class);
in.putExtra("num1", 20.0);
in.putExtra("num2",20.0);
startActivity(in, null, null);
}
@UiThreadTest
public void testOperations(){
mActivity = getActivity();
btnAdd = (Button) mActivity.findViewById(com.example.advancedcalc.R.id.add);
btnSub = (Button) mActivity.findViewById(com.example.advancedcalc.R.id.sub);
btnMul = (Button) mActivity.findViewById(com.example.advancedcalc.R.id.mul);
btnDiv = (Button) mActivity.findViewById(com.example.advancedcalc.R.id.div);
btnDef = (Button) mActivity.findViewById(com.example.advancedcalc.R.id.btnDef);
res = (TextView) mActivity.findViewById(com.example.advancedcalc.R.id.res);
btnAdd.performClick();
assertEquals(40.0 , Double.parseDouble(res.getText().toString()));
btnSub.performClick();
assertEquals(0.0 , Double.parseDouble(res.getText().toString()));
btnMul.performClick();
assertEquals(400.0, Double.parseDouble(res.getText().toString()));
btnDiv.performClick();
assertEquals(1.0 , Double.parseDouble(res.getText().toString()));
btnDef.performClick();
btnAdd.performClick();
assertEquals(1000 , Double.parseDouble(res.getText().toString()));
}
}
Vars是一个将一些默认变量传递给CalcActivity的类。
我的问题是,变量 mockVar 从未使用过。来自 CalcActivity 的所有调用都转到最初存在于 CalcActivty 中的 Vars 类。
谁能指出我在 mockVar 注入方面做错了什么?