Issue
I want to test a Fragment with AndroidTest cases and Mockito (I am using mockito for other test cases).
I´ve done this before with my own code (coded in a different way) but in this case, I am testing a Fragment and I want to mock this call: final PackageManager packageManager = getActivity().getPackageManager();
I will put you here part of the TestClass, and part of the Fragment that I want to test. Thanks in advance for your ideas or suggestions.
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 ...*/
}
}
Solution
I have employed this hack:
// 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;
}
}
Alternatively you could employ reflection to change the value of fragment.mActivity
. I don't know of any other way.
Answered By - Tavian Barnes
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.