How to mock MotionEvent and SensorEvent for unit testing in Android?

How to unit test android SensorEvent and MotionEvent classes?

I need to create one MotionEvent object for unit testing. (We have a obtain method for MotionEvent , which we can use after bullying to create a MotionEvent object)

For the MotionEvent class, I tried using Mockito like:

 MotionEvent Motionevent = Mockito.mock(MotionEvent.class); 

But after the error, I get Android Studio:

 java.lang.RuntimeException: Method obtain in android.view.MotionEvent not mocked. See https://sites.google.com/a/android.com/tools/tech-docs/unit-testing-support for details. at android.view.MotionEvent.obtain(MotionEvent.java) 

After the site mentioned in this error, I added

 testOptions { unitTests.returnDefaultValues = true } 

on build.gradle, but still I get the same error. Any idea on this?

+7
android mockito android-sensors android-testing
source share
2 answers

I finally implemented it for MotionEvent using Roboelectric

 import android.view.MotionEvent; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; import static org.junit.Assert.assertTrue; import org.robolectric.RobolectricGradleTestRunner; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class) public class ApplicationTest { private MotionEvent touchEvent; @Before public void setUp() throws Exception { touchEvent = MotionEvent.obtain(200, 300, MotionEvent.ACTION_MOVE, 15.0f, 10.0f, 0); } @Test public void testTouch() { assertTrue(15 == touchEvent.getX()); } } 

How can we do the same for SensorEvents ?

+3
source share

Here you can make fun of the SensorEvent for the accelerometer event:

 private SensorEvent getAccelerometerEventWithValues( float[] desiredValues) throws Exception { // Create the SensorEvent to eventually return. SensorEvent sensorEvent = Mockito.mock(SensorEvent.class); // Get the 'sensor' field in order to set it. Field sensorField = SensorEvent.class.getField("sensor"); sensorField.setAccessible(true); // Create the value we want for the 'sensor' field. Sensor sensor = Mockito.mock(Sensor.class); when(sensor.getType()).thenReturn(Sensor.TYPE_ACCELEROMETER); // Set the 'sensor' field. sensorField.set(sensorEvent, sensor); // Get the 'values' field in order to set it. Field valuesField = SensorEvent.class.getField("values"); valuesField.setAccessible(true); // Create the values we want to return for the 'values' field. valuesField.set(sensorEvent, desiredValues); return sensorEvent; } 

Change the type or values ​​to suit your use case.

+1
source share

All Articles