androidmockitoexpresso

Mock the method with in instrumented unit test


I am running the Expresso test and I have the requirement to mock the method with context as the parameter. This code is in onStart() of the fragment launch. Since i am running the testcase in emulator, I have to mock the method isBLESupported to return true before the fragment is launched. The code below is written in onStart method.

BreatheMapperUtils utils = new BreatheMapperUtils();
if (utils.isBLESupported(getActivity())) {
    startSyncProcess();
} else {
    //TODO does not run on emulator 
    showNotificationAlert(getString(R.string.ERROR), getString(R.string.BLE_NOT_SUPPORTED), "Ok");
}

Here is my approach to Mock the method before the fragment is launched. But i see that the test cases are executing the real code and mock is not working.

@Before
public void setup() {
    mContext = mActivityTestRule.getActivity();
    BreatheMapperUtils utils = mock(BreatheMapperUtils.class);
    when(utils.isBLESupported(mContext)).thenReturn(true); 
    // launch the fragment
}

But mock is still unsuccessful . Please help if you have any thoughts. Is it possible to mock the method with context? I have read some of the documentation and it says that we cannot use Power Mockito with Expresso test case.


Solution

  • Probably because you create a new instance of BreatheMapperUtils in your onStart. The mock is only effective on the instance you use in your setup method.