Unit Testing

I have an activity that teaches some work in the background and based on the result of this work, one of the other two actions begins. How can I write unit test to test its behavior?

I tried using ActivityUnitTestCase, but it exploded trying to show a progress dialog. With ActivityInstrumentationTestCase2, I could not find a way to intercept the destruction of activity. Any word of advice?

+4
source share
1 answer

ActivityInstrumentationTestCase2 is the right approach as another class is deprecated. To check what happened after your main action, call it ProgressActivity , you should use ActivityMonitor . I think you want to intercept the creation of the Activity , not the destruction.

I assume that ProgressActivity starts another Activity (say A1 , A2 or A3 ) after some calculations are done in the background.

Your test case should look something like this:

 public static final HashSet<Class<? extends Activity>> TARGET_ACTIVITIES = new HashSet<Class<? extends Activity>>(); static { TARGET_ACTIVITIES.add(A1.class); TARGET_ACTIVITIES.add(A2.class); TARGET_ACTIVITIES.add(A3.class); } private static final int TIMEOUT = 7000; public void testRandomActivityStarted() { @SuppressWarnings("unused") ProgressActivity activity = getActivity(); final Instrumentation inst = getInstrumentation(); IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MAIN); intentFilter.addCategory("MY_CATEGORY"); ActivityMonitor monitor = inst.addMonitor(intentFilter, null, false); // Wait, before the Activity started monitor.waitForActivityWithTimeout(TIMEOUT); assertEquals(1, monitor.getHits()); Activity randomActivity = monitor.getLastActivity(); Log.d(TAG, "monitor=" + monitor + " activity=" + randomActivity); // Unfortunately, it seems randomActivity is always null even after a match if ( randomActivity != null ) { assertTrue(TARGET_ACTIVITIES.contains(randomActivity.getClass())); } inst.removeMonitor(monitor); } 

The trick here is to use a category in IntentFilter , because if you rely on getLastActivity() , you may be disappointed, as it seems to always be zero. To fit this category, you must use it when starting A1 , A2 or A3 ( Intent.addCatrgory () )

This example has been adapted from the one that illustrates ActivityMonitor in the Android Application Test Guide .

+4
source

Source: https://habr.com/ru/post/1397506/


All Articles