我一直在尝试使用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注射方面做错了什么吗?
-
我想你错过了
@InjectMocks private CalcActivity mActivity;
-
你用"new"来创建Vars的新对象吗?不确定,但是,我认为应该有一些setter注入,比如[这里需要专家建议]-
public void setVars(Vars vars){ this.vars = vars; }
然后使用此方法注入mock对象。
mActivity.setVars(mockVar);
然后在你清除所有类似-的内容后调用该方法
mActivity.callYourMethodWhichYouAreTesting();