How to properly spy on an Activity

前端 未结 2 1358
一生所求
一生所求 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 activityFactory = new SingleActivityFactory(MainActivity.class) {
            @Override
            protected MainActivity create(Intent intent) {
                subject = spy(getActivityClassToIntercept());
                return subject;
            }
        };
    
        @Rule
        public ActivityTestRule testRule = new ActivityTestRule<>(activityFactory, true, true);
    
        @Test
        public void activity_isBeingSpied() {
            verify(subject).setContentView(R.layout.activity_main);
        }
    
    }
    

提交回复
热议问题