【问题标题】:How to mock MotionEvent and SensorEvent for Unit Testing in android?如何在 android 中模拟 MotionEvent 和 SensorEvent 以进行单元测试?
【发布时间】:2016-04-04 12:10:19
【问题描述】:

如何对 android SensorEventMotionEvent 类进行单元测试?

我需要为单元测试创​​建一个MotionEvent 对象。 (我们有 MotionEventobtain 方法,我们可以在模拟后使用它来创建 MotionEvent 自定义对象)

对于 MotionEvent 类,我尝试过 Mockito 之类的:

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

但我在 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)

按照这个错误中提到的网站,我添加了

testOptions {
        unitTests.returnDefaultValues = true
    }

在 build.gradle 上,但我仍然遇到同样的错误。对此有什么想法吗?

【问题讨论】:

标签: android mockito android-sensors android-testing


【解决方案1】:

以下是您可以为加速度计事件模拟 SensorEvent 的方法:

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

根据您的用例更改类型或值。

【讨论】:

    【解决方案2】:

    我终于用RoboelectricMotionEvent实现了它

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

    我们如何为SensorEvents 做同样的事情?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-30
      • 2013-11-18
      • 2013-03-25
      • 1970-01-01
      • 2018-04-04
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多