How to properly spy on an Activity

You can use Robolectric to create your own proxy (or as Robolectric calls them "Shadows") to your activity,

When you create the proxy you can create your own setters that can trigger the real object methods,

How to create a shadow example:

@Implements(Bitmap.class)
public class MyShadowBitmap {

@RealObject private Bitmap realBitmap;
private int bitmapQuality = -1;

@Implementation
public boolean compress(Bitmap.CompressFormat format, int quality, OutputStream stream) {
  bitmapQuality = quality;
  return realBitmap.compress(format, quality, stream);
}

public int getQuality() {
  return bitmapQuality;
}
}
}

when the @RealObject is your real instance,

To use this shadow using Robolectric test runner define a new test class as follows:

@RunWith(RobolectricTestRunner.class)
@Config(shadows = MyShadowBitmap.class)
public class MyTestClass {}

To pull the current shadow instance use the method:

shadowOf()

And in any case, here is s link to Robolectric:

http://robolectric.org/custom-shadows/


Using:

android Test Support library's SingleActivityFactory, ActivityTestRule and Mockito's spy()

dependencies {
  androidTestImplementation 'com.android.support.test:runner:1.0.2'
  androidTestImplementation 'com.android.support.test:rules:1.0.2'
  androidTestImplementation 'org.mockito:mockito-android:2.21.0'
}

Outline:

inject the spied instance inside SingleActivityFactory's implementation

Code:

public class MainActivityTest {
    MainActivity subject;

    SingleActivityFactory<MainActivity> activityFactory = new SingleActivityFactory<MainActivity>(MainActivity.class) {
        @Override
        protected MainActivity create(Intent intent) {
            subject = spy(getActivityClassToIntercept());
            return subject;
        }
    };

    @Rule
    public ActivityTestRule<MainActivity> testRule = new ActivityTestRule<>(activityFactory, true, true);

    @Test
    public void activity_isBeingSpied() {
        verify(subject).setContentView(R.layout.activity_main);
    }

}