jeudi 31 décembre 2015

Android - How can I mock a lack of camera when testing my app?

I would like to check that my app shows an error message when the device it is running on has no camera. I have tried passing in a mock context but mockito gives an error when I try to mock the CameraManager class as it is declared final. Surely android has a simple solution for this? Here's my attempt:

public class CreateNewIdentityActivityUnitTest extends ActivityUnitTestCase<CreateNewIdentityActivity> {
    public CreateNewIdentityActivityUnitTest() {
        super(CreateNewIdentityActivity.class);
    }

    public void testErrorMessageDisplayedWhenNoCamerasExist() throws Exception {
        // Create the mock cameramanager
        // THIS LINE FAILS BECAUSE CAMERAMANAGER IS FINAL
        CameraManager mockCameraManager = mock(CameraManager.class);
        String[] cameraIdList = {};
        when(mockCameraManager.getCameraIdList()).thenReturn(cameraIdList);

        // Create the mock context
        Context mockContext = mock(Context.class);
        when(mockContext.getSystemService(Context.CAMERA_SERVICE)).thenReturn(mockCameraManager);

        // Start the activity
        Intent intent = new Intent(mockContext, CreateNewIdentityActivity.class);
        Activity activity = startActivity(intent, null, null);

        // Verify that the error message was made visible
        TextView errorTextView = (TextView)activity.findViewById(R.id.ErrorTextView);
        assertNotNull(errorTextView);
        assertEquals(View.VISIBLE, errorTextView.getVisibility());
    }
}

Aucun commentaire:

Enregistrer un commentaire