Search code examples
androidunit-testingaccelerometer

How can I unit test an Android Activity that acts on Accelerometer?


I am starting with an Activity based off of this ShakeActivity and I want to write some unit tests for it. I have written some small unit tests for Android activities before but I'm not sure where to start here. I want to feed the accelerometer some different values and test how the activity responds to it. For now I'm keeping it simple and just updating a private int counter variable and a TextView when a "shake" event happens.

So my question largely boils down to this:

How can I send fake data to the accelerometer from a unit test?


Solution

  • My solution to this ended up way simpler then I expected. I'm not really testing the accelerometer so much as I am testing the application's response to an event raised by the accelerometer, and I just needed to test accordingly. My class implements SensorListener and I wanted to test what happens onSensorChanged. The key then was to feed in some values and check my Activity's state. Example:

    public void testShake() throws InterruptedException {
        mShaker.onSensorChanged(SensorManager.SENSOR_ACCELEROMETER, new float[] {0, 0, 0} );
        //Required because method only allows one shake per 100ms
        Thread.sleep(500);
        mShaker.onSensorChanged(SensorManager.SENSOR_ACCELEROMETER, new float[] {300, 300, 300});
        Assert.assertTrue("Counter: " + mShaker.shakeCounter, mShaker.shakeCounter > 0);
    }