lundi 26 octobre 2015

Change network in Android unit test?

I am testing my broadcast receiver that responds to network changes. How do I toggle connectivity off or on?

This is what I have so far:

public class NetworkChangeReceiverTest extends AndroidTestCase{

private NetworkChangeReceiver mNetworkChangeReceiver;
private TestContext testContext;

@Override
protected void setUp() throws Exception {
    super.setUp();

    mNetworkChangeReceiver = new NetworkChangeReceiver();
    testContext = new TestContext();
}

public void testOnReceive() {
    Intent intent = new Intent("android.net.conn.CONNECTIVITY_CHANGE");
    mNetworkChangeReceiver.onReceive(getContext(), intent);
    assertEquals(0, testContext.getReceivedIntents().size());
}

public class TestContext extends MockContext {

    private List<Intent> mReceivedIntents = new ArrayList<Intent>();

    @Override
    public String getPackageName() {
        return "com.mypackage.test";
    }

    @Override
    public void startActivity(Intent xiIntent) {
        mReceivedIntents.add(xiIntent);
    }

    public List<Intent> getReceivedIntents() {
        return mReceivedIntents;
    }
}
}

Also is there another way to test if the BroadcastReceiver starts an intent?

Aucun commentaire:

Enregistrer un commentaire