我尝试使用espresso初始化我的活动并模拟onCreate,但没有在我的项目中添加Dagger时找不到好的解决方案:
@Rule
public ActivityTestRule<MyActivity> mActivityRule = new ActivityTestRule<>(MyActivity.class);
我还试图创建一个自定义规则,但这没有用,因为我无法在创建活动之前模拟活动... 只有在创建之后,才会调用当时的onCreate。
public class MyCustomRule<A extends MyActivity> extends ActivityTestRule<A> { ....
@Override
protected void beforeActivityLaunched(){super.beforeActivityLaunched();}
@Override
protected Intent getActivityIntent() {...}
@Override
protected void afterActivityLaunched() {...}
@Override
protected void afterActivityFinished() {...}
}
答案 0 :(得分:1)
private SingleActivityFactory<MyActivity> injectedFactory = new SingleActivityFactory<MyActivity>(MyActivity.class) {
@Override
protected MyActivity create(Intent intent) {
MyActivity activity = new MockMyActivity();
return activity;
}
};
并使用它来创建规则
@Rule
public ActivityTestRule<MyActivity> mActivityRule = new ActivityTestRule<>(injectedFactory, false, true);
你的MockMyActivity.class看起来像这样:
public class MockMyActivity extends MyActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// you can add some of your logic here
}
@Override
protected MyFragment findOrCreateViewFragment() {
MyFragment myFragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.contentFrame);
if (myFragment == null) {
//spy-mock your fragment
myFragment = spy(new MyFragment());
// ex do not load data from the web service
doNothing().when(myFragment).callLoadMyService();
ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), myFragment, R.id.contentFrame);
}
return myFragment;
}