Search code examples
javaandroidmultithreadingjunitinstrumentation

How do I interact with UI Components from within ActivityInstrumentationTestCase2?


I'm trying to learn how to write instrumentation tests for Android. I have a class which extends ActivityInstrumentationTestCase2 in order to test my Activity. In one of my tests I try to do the following:

Button button = (Button) getActivity().findViewById(R.id.my_button);
button.performClick() // this method throws CalledFromWrongThreadException

From reading around it sounds like I can't interact with UI components in this way - I have to either create a new runnable and run it on the UI thread (Testing with UI elements in Android view) or run the whole test on the UI thread using @UiThreadTest (Android: Only the original thread that created a view hierarchy can touch its views - UnitTest). However, the former solution is very cumbersome and the latter simply didn't work for me (the same exception gets thrown).

What I would like is to be able to interact directly with the button as the testing fundamentals documentation seems to suggest is possible (at least for a Spinner). Is this possible or do I have to worry about running on different threads like the first link suggests?


Solution

  • As explained by Muhammed Babar in the comments, I needed to use TouchUtils.clickView()