views:

601

answers:

3

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?

+1  A: 

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

AFAIK, you can't.

Have your shaker logic accept a pluggable data source. In the unit test, supply a mock. In production, supply a wrapper around the accelerometer.

Or, don't worry about unit testing the shaker itself, but rather worry about unit testing things that use the shaker, and create a mock shaker.

CommonsWare
That certainly makes sense and does sound like a better idea. Do you have any examples of using a "pluggable data source" like this?
Corey Sunwold
A: 

Well, you can write an interface.

interface IAccelerometerReader {
    public float[] readAccelerometer();
}

The write an AndroidAccelerometerReader and FakeAccelerometerReader. Your code would use IAccelerometerReader but you can swap in the Android or Fake readers.

Ray
+1  A: 

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 applications 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 Activities 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);
}
Corey Sunwold