How to properly spy on an Activity

前端 未结 2 1359
一生所求
一生所求 2020-12-16 09:51

Mockito creates a proxy instance when some thing is spied on. Now, is there any way to forward setters that are then executed on that proxy instance to the real instance tha

相关标签:
2条回答
  • 2020-12-16 10:34

    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);
        }
    
    }
    
    0 讨论(0)
  • 2020-12-16 10:44

    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/

    0 讨论(0)
提交回复
热议问题