Reputation: 501
I have a class that implements a SensorEventListener and listens for Accelerometer events:
public class MyListener implements SensorEventListener {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
}
I would like to test onSensorChanged method using Robolectric,
any ideas as to how to achieve this?
Upvotes: 2
Views: 661
Reputation: 501
1) Get the sensor manager shadow
2) Register the required sensor
3) Get listeners list from the sensor manager (it's private so use reflection)
4) Create the SensorEvent and trigger the onSensorChanged methos
@Before
public void init() {
SensorManager sensorManager = (SensorManager) RuntimeEnvironment.application.getSystemService(Context.SENSOR_SERVICE);
sensorManagerShadow = shadowOf(sensorManager)
Sensor sensor = Shadow.newInstanceOf(Sensor.class);
sensorManagerShadow.addSensor(Sensor.TYPE_ACCELEROMETER, sensor);
}
@Test
public void myTest() throws Exception {
SensorEvent event = sensorManagerShadow.createSensorEvent();
Field field = ShadowSensorManager.class.getDeclaredField("listeners");
field.setAccessible(true);
List<SensorEventListener> listeners = (List<SensorEventListener>)field.get(this);
listeners.get(0).onSensorChanged(event);
}
Upvotes: 2