开发者

How to add and remove packages in android Junit tests in android?

开发者 https://www.devze.com 2023-03-11 23:21 出处:网络
How can I add and remove packages 开发者_Python百科in jUnit tests in android? I am building an app that has to react to packages being added and removed (packages other than the one being tested), an

How can I add and remove packages 开发者_Python百科in jUnit tests in android?

I am building an app that has to react to packages being added and removed (packages other than the one being tested), and I would like to be able to test that functionality in jUnit tests.

Any suggestions?


Since you didn't give much info, my answer assumes you are using a Service or Activity since those cases are probably the ones you are having trouble with. If you are just dealing with a BroadcastReceiver then call onReceive on your BroadcastReceiver directly.

Here is some code that should get you going:

public class MyTests extends AndroidTestCase {

private BroadcastReceiver mPackageAddedReceiver;

@Override
protected void setUp() throws Exception
{
    super.setUp();
    this.setContext(new MyContextWrapper(getContext()));
}

public void test_PackageAdded_AssertStuff()
{
    Intent packageAdded = new Intent(Intent.ACTION_PACKAGE_ADDED);
    packageAdded.setData(Uri.parse("package://my.package"));
    mPackageAddedReceiver.onReceive(getContext(), packageAdded);

    // Do Asserts
}

private class MyContextWrapper extends ContextWrapper
{
    public MyContextWrapper(Context base)
    {
        super(base);
    }

    @Override
    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
            String broadcastPermission, Handler scheduler)
    {
        if (filter.hasAction(Intent.ACTION_PACKAGE_ADDED)) {
            mPackageAddedReceiver = receiver;
        }

        return super.registerReceiver(receiver, filter, broadcastPermission, scheduler);
    }
}; }

You will probably want to add more actions that you support.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号