2015-12-30 72 views
7

如何單元測試android SensorEventMotionEvent類?如何在android中爲單元測試模擬MotionEvent和SensorEvent?

我需要爲單元測試創​​建一個MotionEvent對象。 (我們有obtain方法MotionEvent,我們可以嘲諷後使用它來創建MotionEvent自定義對象)

對於MotionEvent類,我試圖與Mockito像:

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

但下面的錯誤,我在Android工作室獲得:

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 
    } 

on build.gradle,但我仍然得到這個相同的錯誤。對此有何想法?

+1

對於SensorEvent,示例:https://medium.com/@jasonhite/testing-on-android-sensor-events-5757bd61e9b0#.nx5mgk6sq – Kikiwa

回答

3

我以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同樣的事情終於實現了它的MotionEvent

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

更改爲適合於您的使用案例的類型或值。