2015-12-30 10 views
7

Come testare le unità Android SensorEvent e le classi MotionEvent?Come simulare MotionEvent e SensorEvent per il test delle unità in Android?

Devo creare un oggetto MotionEvent per il test dell'unità. (Abbiamo obtain metodo per MotionEvent che possiamo usare dopo beffardo per creare l'oggetto MotionEvent personalizzato)

Per la classe MotionEvent, ho provato con Mockito come:

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

Ma seguente errore sto ottenendo su 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) 

a seguito del sito citato su questo errore, ho aggiunto

testOptions { 
     unitTests.returnDefaultValues = true 
    } 

su build.gradle, ma continuo a ricevere lo stesso errore. Qualche idea su questo?

+1

Per SensorEvent, un esempio: https://medium.com/@jasonhite/testing-on-android-sensor-events-5757bd61e9b0#.nx5mgk6sq – Kikiwa

risposta

3

ho finalmente implementato per MotionEvent utilizzando 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()); 
    } 
} 

Come possiamo fare la stessa cosa per SensorEvents?

1

Ecco come si potrebbe prendere in giro un SensorEvent per un evento accelerometro:

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

Cambiare il tipo o il valore a seconda della caso d'uso.

Problemi correlati