Search code examples
android-cameraandroid-espressoandroid-uiautomator

Click on Camera Shutter using UIAutomator


I am writing an Espresso test for my app, and am trying to automate clicking the shutter button after opening of a camera in my app.

I am using Espresso and UIAutomator in the Android Emulator. I managed to dump this UI in UIAutomatorViewer. UIAutomatorViewer

I can't figure out why I am unable to click on the shutter button using UIAutomator using this code:

public void clickCameraShutterButton() throws UiObjectNotFoundException
{
    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    UiSelector shutterSelector = new UiSelector().resourceId("com.android.camera:id/shutter_button");
    UiObject shutterButton = device.findObject(shutterSelector);
    shutterButton.click();
}

The camera just sits there, and the shutter button is never clicked. This is the stack trace I'm getting in the Android Studio monitor:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference

Any advice would be appreciated.


Solution

  • This worked for me

    @Before
    public void setUp() {
        // Initialize UiDevice instance
        final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
        mDevice = UiDevice.getInstance(instrumentation);
    }
    
    ...
    
    
    /**
     * @@Test comment here@@
     *
     * @throws Exception
     */
    @Test
    public void culebraGeneratedTest_CameraShutter() throws Exception {
        mDevice.findObject(By.res("com.android.camera2:id/shutter_button").desc("Shutter").clazz("android.widget.ImageView").text(Pattern.compile("")).pkg("com.android.camera2")).clickAndWait(Until.newWindow(), DEFAULT_TIMEOUT);
    }
    

    This test finds the shutter and clicks on it.

    If you are interested this test was automatically generated using CulebraTester.