【发布时间】:2015-02-22 16:52:08
【问题描述】:
我有一个控制器类来处理片段创建。让我们像下面这样说:
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);
}
}
在我的测试(标准 Junit4 测试类)中,我有:
@Test
public void testNewInstanceCreteMultipleData() throws Exception {
Fragment f = FragmentController.newInstance("Hello", 5);
assertTrue("MultipleDataFragment should be created"
, f instanceOf MultipleDataFragment);
}
因为我没有模拟 Bundle,所以我得到了。
java.lang.RuntimeException: Method putString not mocked.Set
问题是如何模拟 Bundle 对象以便可以执行测试?我是否需要在每个类中创建 Bundle 对象并使用它来代替静态方法,还是有更好的方法?
对此的任何示例表示赞赏。
【问题讨论】:
-
请注意,您的 getInstance() 方法不完整。他们甚至没有返回语句。
标签: java android unit-testing