android-studiounit-testingtestinginstrumented-test

Running an instrumented test in Android Studio without simulating user actions


I have written some code that manipulates MotionEvent instances, and want to write a unit test for it.

The unit test needs to validate my manipulations only; it does not need to simulate any user actions.

I understand it needs to be an instrumented test to be able to use the methods of MotionEvent; I need the actual methods, not any mocking.

I have defined an instrumented test in the directory src/androidTest/...; however, it still throws the exception

java.lang.RuntimeException: Method obtain in android.view.MotionEvent not mocked.

My build.gradle file for the module has the following entries:

defaultConfig {
    ...
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
...
dependencies {
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

The imports in my test class are as follows:

import android.view.MotionEvent;
import org.junit.Test;
import static org.junit.Assert.*;

How can I run this test?


Solution

  • My mistake was as follows.

    I initially thought that a local unit test would suffice, since no user action was involved.

    It turned out to be wrong: the local unit tests do not get access to the Android methods.

    I moved my file containing the test, to the place prescribed for the instrumented tests, /src/androidTest/java/, but did not change the file; this can be seen in my imports.

    For this reason it still ran as a local non-instrumented test.

    After I realized it, I changed the file to mimic the ExampleInstrumentedTest created by Android studio together with my project. I also deleted the run configuration which was still a local test.

    After that Android studio prompted me to create a new run configuration, and the test ran successfully.