Android测试:在接收广播接收器时更新listview

时间:2013-11-19 13:54:26

标签: android listview testing broadcastreceiver android-context

MyListActivity.java有一个私有的BroadcastReceiver,它会在收到广播时立即更新ListView。我想测试在收到广播后列表视图是否得到更新。但是我遇到了MockContext的问题。

这就是我的测试。

public class MyListActivityTest extends ActivityInstrumentationTestCase2<MyListActivity>{
public void setUp()
{
    super.setUp();

    setActivityInitialTouchMode(false);

    mActivity = getActivity();
    myList = (ListView) mActivity.findViewById(R.id.myList);
        mContext = new MockContext();

}

public void testListUpdate()
{
    Intent in = new Intent("LIST_ITEM");
    in.putExtra("ITEM_VAL", "test2");

    try {
        Method method = MyListActivity.class.getMethod("getReceiver", null);
        BroadcastReceiver br = (BroadcastReceiver)method.invoke(mActivity, null);

        assertNotNull(br);

                    ArrayList<Item> list = new ArrayList<Item>();
                    list.add(new Item("test1"));
        ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(mActivity, android.R.layout.simple_list_item_1, list);     
            myList.setAdapter(adapter);

        br.onReceive(mContext, in);
        assertEquals(myList.getAdapter().getCount(), 1);
    }
            catch {..}
}

这给了我一个CalledFromWrongThreadException,我猜是因为应该初始化适配器并在MockContext实例mContext中设置。但是如果我用mContext替换ArrayAdapter构造函数中的参数mActivity,它会在ArrayAdapter.init-&gt;中抛出UnsupportedOperationException。 MockContext.getSystemService。

请告诉我如何在与接收器相同的上下文中初始化适配器,以便在onReceive之后适配器更新,我可以检查适配器大小是否增加1?

我有一个选项就是监视我的数据源,无论它是否得到更新,然后我的onReceive调用添加到适配器,这是抛出错误的那个!

1 个答案:

答案 0 :(得分:1)

要在UI线程上运行某些内容,您可能需要调用runTestOnUiThread

runTestOnUiThread(new Runnable() {
    @Override
    public void run() {
        // Here the actions you want to perform
    }
});

这将避免CalledFromWrongThreadException