如何在Android Unit-Test中模拟Bundle方法? [英] How to mock Bundle method in Android Unit-Test?

查看:268
本文介绍了如何在Android Unit-Test中模拟Bundle方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个处理片段创建的控制器类。让我们说如下:

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);
    }
}

在我的测试中(标准Junit4测试类)我有:

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);
}

因为我没有嘲笑Bundle,所以我得到了。

Since I didn't mock the Bundle, I'm getting.

java.lang.RuntimeException: Method putString not mocked.Set

问题是如何模拟Bundle对象以便执行测试?我是否需要在每个创建Bundle对象的类中使用静态方法并使用它来代替或者是否有更好的方法?

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.

推荐答案

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

One way could be to use a powerful mocking framework like PowerMock, which can even intercept the construction of new objects.

这应该对你有用,但是像Bundle一样模拟简单类意味着一些努力 - 你也可以使用 UnMock插件来实现真正的实现。

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.

这篇关于如何在Android Unit-Test中模拟Bundle方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆