如何在调用 onCreate 之前获取 Activity 的引用。虽然它正在测试中。我使用 ActivityTestRule 作为 JUnit 规则。这个要求的原因是我想将 Mocks 注入到来自测试的活动中。
public class MyActivity extends Activity{
MyComponent myComponent;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if(myComponent==null){
myComponent ... //initialise dagger component
}
myComponent.inject(this);
...
}
public void setComponent(MyComponent comp){
this.myComponent = comp;
}
}
public class MyTest{
@Rule
public ActivityTestRule<MyActivity> intentsTestRule = new ActivityTestRule<>(MyActivity.class);
MyComponent myFakeComponent;
@Before
public void setUp() {
MyActivity activity = intentsTestRule.getActivity();
activity.setComponent(myFakeComponent);
}
@Test
public void testMethod1(){...}
}