No need to test the OS's accelerometer, just test your own logic that responds to the OS - in other words your SensorListener
. Unfortunately SensorEvent
is private and I could not call SensorListener.onSensorChanged(SensorEvent event)
directly, so had to first subclass SensorListener with my own class, and call my own method directly from the tests:
public class ShakeDetector implements SensorEventListener {
@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
onSensorUpdate(x, y, z);
}
public void onSensorUpdate(float x, float y, float z) {
// do my (testable) logic here
}
}
Then I can call onSensorUpdated
directly from my test code, which simulates the accelerometer firing.
private void simulateShake(final float amplitude, int interval, int duration) throws InterruptedException {
final SignInFragment.ShakeDetector shaker = getFragment().getShakeSensorForTesting();
long start = System.currentTimeMillis();
do {
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
shaker.onSensorUpdate(amplitude, amplitude, amplitude);
}
});
Thread.sleep(interval);
} while (System.currentTimeMillis() - start < duration);
}