如何在android中为单元测试模拟MotionEvent和SensorEvent?

如何单元测试的Android SensorEventMotionEvent类?

我需要为单元测试创​​建一个MotionEvent对象。 (我们已经obtainMotionEvent方法,我们可以在MotionEvent之后使用它来创建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,但我仍然得到这个相同的错误。 对此有何想法?


我终于实现了它的MotionEvent使用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());
    }
}

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


以下是您可以如何为加速度计事件模拟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;
}

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

链接地址: http://www.djcxy.com/p/89533.html

上一篇: How to mock MotionEvent and SensorEvent for Unit Testing in android?

下一篇: Selenium give file name when downloading