Question

I've been trying to test a sample app using Mockito.

My test case:

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 is a class that passes some default variables into the CalcActivity.

My problem is that, the variable mockVar is never used. All calls from CalcActivity goes to the Vars class that is originally present in the CalcActivty.

Can anyone point what i'm doing wrong regarding mockVar injection ?

No correct solution

OTHER TIPS

  • I think you have missed -

    @InjectMocks private CalcActivity mActivity;

  • Are you using "new" for creating new object of Vars? Not sure but, I think there should be having some setter injection like [ Need experts advise here ] -

    public void setVars(Vars vars){ this.vars = vars; }

And then inject your mock object using this method.

mActivity.setVars(mockVar);
  • Then call the method after you stubbed everything like -

    mActivity.callYourMethodWhichYouAreTesting();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top