Fastest way to create a mock Activity for testing
With androidX libraries, you can use ActivityScenario
.
Simply import androidTestImplementation("androidx.test:core:1.2.0")
in your app.gradle file
Then, in your instrumented test, import ActivityScenario
and launch the activity with:
import androidx.test.core.app.ActivityScenario
@Test
fun testActivity() {
ActivityScenario.launch(MainActivity::class.java).onActivity { activity ->
// do something with your activity instance
}
}
Solved! Here's what I did:
- In the test project, I removed the target package in the instrumentation tab and added it again pointing to the test project base package, where the mock activity is.
- Added the target library as an Android Library in my test project. (Right click over test project -> properties -> Android -> Library -> added the target library).
- Added the mock activity in the test project manifest.
To solve the exception I posted above, just replaced the test case constructor with this one:
public LibraryTest() { super(MockActivity.class); }
Now that works and I can successfully launch dialogs. But in my brief research I stumbled upon Robotium. This library is just amazing. It is not needed for what I was trying to do at first, but I found it very useful to test GUIs in an automated way. Now I have a fresh new activity recreated in each setUp
call.