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

后端 未结 5 1070
心在旅途
心在旅途 2021-01-03 04:00

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 befor

5条回答
  •  伪装坚强ぢ
    2021-01-03 04:32

      public  class SensorService implements SensorEventListener {
    /**
         * Accelerometer values
         */
        private float accValues[] = new float[3];
         @Override
         public void onSensorChanged(SensorEvent event) {
    
              if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                accValues[0] = sensorEvent.values[0];
                accValues[1] = sensorEvent.values[1];
                accValues[2] = sensorEvent.values[2];
            }
    
         }
    } 
    

    you can test above piece of code by following way

    @Test
        public void testOnSensorChangedForAcceleratorMeter() throws Exception {
            Intent intent=new Intent();
            sensorService.onStartCommand(intent,-1,-1);
    
            SensorEvent sensorEvent=getEvent();
            Sensor sensor=getSensor(Sensor.TYPE_ACCELEROMETER);
            sensorEvent.sensor=sensor;
            sensorEvent.values[0]=1.2345f;
            sensorEvent.values[1]=2.45f;
            sensorEvent.values[2]=1.6998f;
            sensorService.onSensorChanged(sensorEvent);
    
            Field field=sensorService.getClass().getDeclaredField("accValues");
            field.setAccessible(true);
            float[] result= (float[]) field.get(sensorService);
            Assert.assertEquals(sensorEvent.values.length,result.length);
            Assert.assertEquals(sensorEvent.values[0],result[0],0.0f);
            Assert.assertEquals(sensorEvent.values[1],result[1],0.0f);
            Assert.assertEquals(sensorEvent.values[2],result[2],0.0f);
        } 
    
    
    
    
    private Sensor getSensor(int type) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
                Constructor constructor = Sensor.class.getDeclaredConstructor(new Class[0]);
                constructor.setAccessible(true);
                Sensor sensor= constructor.newInstance(new Object[0]);
    
                Field field=sensor.getClass().getDeclaredField("mType");
                field.setAccessible(true);
                field.set(sensor,type);
                return sensor;
            }
    
    
    
    private SensorEvent getEvent() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
            Constructor constructor = SensorEvent.class.getDeclaredConstructor(int.class);
            constructor.setAccessible(true);
            return constructor.newInstance(new Object[]{3});
        }
    

提交回复
热议问题