我有一个实现SensorEventListener的类并侦听Accelerometer事件:
public class MyListener implements SensorEventListener {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
}
我想使用Robolectric测试onSensorChanged方法,
关于如何实现这一点的任何想法?
答案 0 :(得分:2)
1)获取传感器管理器阴影
2)注册所需的传感器
3)从传感器管理器获取侦听器列表(它是私有的,因此使用反射)
4)创建SensorEvent并触发onSensorChanged方法
@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);
}