java - 如何在 Android 单元测试中模拟 Bundle 方法?

标签 java android unit-testing

我有一个处理 fragment 创建的 Controller 类。让我们像下面这样说:

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 对象的类中使用静态方法并改用它,或者是否有更好的方法?

对此的任何示例表示赞赏。

最佳答案

一种方法可能是使用强大的模拟框架,如 PowerMock ,甚至可以拦截新对象的构造。

这应该对你有用,但是模拟像 Bundle 这样的“简单”类需要一些努力——你也可以通过使用 UnMock plugin 来使用真正的实现。 .

关于java - 如何在 Android 单元测试中模拟 Bundle 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28660507/

相关文章:

Java 反射 : Is the order of class fields and methods standardized?

java - 我可以使用超过 32 GB 的堆和压缩 oops

java - 元素在 XPath Checker 中找到,但在 Selenium 中找不到

javascript - 如何对 node js express 应用程序进行单元测试

java - 通过多个jsp页面倒计时

java - 如何修复“JPasswordField 中的 getText() 已被弃用”

android - 在 Android 上构建 libloc_api

android - 使用两行不同的字体创建微调器下拉菜单

java - 为什么我在 androidmanifest.xml 中使用 configchanges 声明的 adactivity 时出现此错误

java.lang.IllegalStateException : missing behavior definition for the preceding method call getMessage ("title")