我想用AndroidTest用例和Mockito测试Fragment(我在其他测试用例中使用Mockito)。
我以前用自己的代码(以不同的方式编码)做过这件事,但在这种情况下,我正在测试一个Fragment,我想模拟这个调用:final PackageManager PackageManager=getActivity().getPackageManager();
我将把TestClass的一部分和我想要测试的Fragment的一部分放在这里。提前感谢您的想法或建议。
public class MyFragmentTest extends
ActivityInstrumentationTestCase2<MyActivity>{
MyFragment myFragment;
public MyFragmentTest () {
super(MyActivity.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
// This have to be done because of some issues with dexmaker
System.setProperty("dexmaker.dexcache", "/sdcard");
// This have to be done because of the sharedUserId problem
Thread.currentThread().setContextClassLoader(
getClass().getClassLoader());
myFragment = new MyFragment() {
//I can override methods here
};
}
public void testMyMethod() throws Exception {
myFragment.methodThatIWantToTest();
}
}
/************ CLASS THAT I WANT TO TEST *********/
public class MyFragment extends Fragment{
public void methodThatIWantToTest(){
/*..... more lines */
final PackageManager packageManager = getActivity().getPackageManager();
/*..... more lines ...*/
}
}
我使用了这个破解:
// Needed because Fragment.mActivity is package-private
package android.support.v4.app;
public class FragmentInjector {
public static void injectActivity(Fragment fragment, FragmentActivity fragmentActivity) {
fragment.mActivity = fragmentActivity;
}
}
或者,您可以使用反射来更改fragment.mActivity
的值。我不知道还有别的办法。