Reputation: 5969
I have one controller class that handle Fragment creation. Let's say like below:
public class FragmentController {
public static Fragment newInstance(String title, int total) {
return total > 0? MultipleDataFragment.newInstance(title, total)
: SingleDataFragment.newInstance(title);
}
}
public class MultipleDataFragment extends Fragment {
public static MultipleDataFragment newInstance( String title, int total) {
Bundle b = new Bundle();
b.putString("title", title);
b.putInt("total", total);
}
}
public class SingleDataFragment extends Fragment {
public static SingleDataFragment newInstance( String title, int total) {
Bundle b = new Bundle();
b.putString("title", title);
b.putInt("total", total);
}
}
In my test (standard Junit4 test class) I have:
@Test
public void testNewInstanceCreteMultipleData() throws Exception {
Fragment f = FragmentController.newInstance("Hello", 5);
assertTrue("MultipleDataFragment should be created"
, f instanceOf MultipleDataFragment);
}
Since I didn't mock the Bundle, I'm getting.
java.lang.RuntimeException: Method putString not mocked.Set
The question is how do I mock the Bundle object so the test can be executed? Do I need static method inside each class that create Bundle object and use that instead or is there a better approach to this?
Any example to this is appreciated.
Upvotes: 4
Views: 6586
Reputation: 1523
Use the Unmock plugin to un-mock the Bundle class. You'll need to un-mock with Android 4.4 (unmock 'org.robolectric:android-all:4.4_r1-robolectric-1'
) since later versions of Android reference non-standard Java methods.
You'll also need to keep ArrayMap and MapCollections.
Upvotes: 0
Reputation: 61
One way could be to use a powerful mocking framework like PowerMock, which can even intercept the construction of new objects.
This should work for you but mocking "simple" classes like Bundle means some effort - you could also use the real implementation by using the UnMock plugin.
Upvotes: 6