2015-12-30 6 views
7

यूनिट परीक्षण कैसे करें एंड्रॉइड SensorEvent और MotionEvent कक्षाएं?एंड्रॉइड में यूनिट परीक्षण के लिए मोशनवेन्ट और सेंसरवेन्ट का नकल कैसे करें?

मुझे यूनिट परीक्षण के लिए एक MotionEvent ऑब्जेक्ट बनाने की आवश्यकता है।

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

लेकिन निम्न त्रुटि मैं पर Android स्टूडियो हो रही है:

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 को शामिल किया है

build.gradle पर, लेकिन फिर भी मुझे यह त्रुटि मिल रही है। इस पर कोई विचार है?

+1

सेंसरएवेंट के लिए, एक उदाहरण: 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

यहां आपके द्वारा किसी accelerometer घटना के लिए एक 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; 
} 

बदलें प्रकार या मान आपके उपयोग के मामले के लिए उपयुक्त है।

संबंधित मुद्दे

 संबंधित मुद्दे