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

后端 未结 5 1458
心在旅途
心在旅途 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:38

    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);
    }
    

提交回复
热议问题