dimanche 22 février 2015

How to mock Bundle method in Android Unit-Test?

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.


Aucun commentaire:

Enregistrer un commentaire