2015-12-30 13 views
7

ユニットアンドロイドSensorEventMotionEventクラスをどのようにユニットテストするのですか?ユニットテストのためのMotionEventとSensorEventをアンドロイドでモックする方法は?

ユニットテスト用にMotionEventオブジェクトを1つ作成する必要があります。私はAndroidのメーカーに取得しています

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

しかし、次のエラー:MotionEventクラスの

(私たちはMotionEventカスタムオブジェクトを作成するために、私たちが嘲笑した後に使用することができますMotionEventためobtain方法を持っている)、私のようなMockitoで試してみました:

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) 

このエラーに言及したサイトに続いて、私は

012を追加しました

on build.gradleでも、この同じエラーが発生しています。これについてのアイデア?

+1

SensorEventの場合、例:https://medium.com/@jasonhite/testing-on-android-sensor-events-5757bd61e9b0#.nx5mgk6sq – Kikiwa

答えて

3

私は最終的にどのように我々はSensorEventsために同じことを行うことができます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()); 
    } 
} 

を使用して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; 
} 

変更ご使用の場合に適切なタイプまたは値。

関連する問題