Robolectric

Vincent Nien

Activity Testing

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final CheckBox checkBox = (CheckBox) findViewById(R.id.wifi_only);
        boolean check = getSharedPreferences("settings", Context.MODE_PRIVATE).getBoolean("wifi_only", true);
        checkBox.setChecked(check);

        RxCompoundButton
                .checkedChanges(checkBox)
                .throttleWithTimeout(500L, TimeUnit.MILLISECONDS)
                .subscribe(checked -> {
                    getSharedPreferences("settings", Context.MODE_PRIVATE)
                            .edit()
                            .putBoolean("wifi_only", checked)
                            .apply();
                });
    }

Activity Testing

    @Test
    public void testDefaultChecked() {
        SharedPreferences sharedPrefs = RuntimeEnvironment.application.getSharedPreferences("settings",
                                       Context.MODE_PRIVATE);
        boolean checked = sharedPrefs.getBoolean("wifi_only", true);

        MainActivity activity = Robolectric.setupActivity(MainActivity.class);
        CheckBox box = (CheckBox) activity.findViewById(R.id.wifi_only);

        assertEquals(checked, box.isChecked());
    }


    @Test
    public void testDefaultChecked1() {
        SharedPreferences sharedPrefs = RuntimeEnvironment.application.getSharedPreferences("settings",
                                      Context.MODE_PRIVATE);
        sharedPrefs.edit().putBoolean("wifi_only", false).commit();
        boolean checked = sharedPrefs.getBoolean("wifi_only", true);

        MainActivity activity = Robolectric.setupActivity(MainActivity.class);
        CheckBox box = (CheckBox) activity.findViewById(R.id.wifi_only);

        assertEquals(checked, box.isChecked());
    }

Activity Testing

    @Test
    public void testClickCheckBox() {
        SharedPreferences sharedPrefs = RuntimeEnvironment.application.getSharedPreferences("settings", 
                                           Context.MODE_PRIVATE);
        sharedPrefs.edit().putBoolean("wifi_only", true).commit();

        boolean isWifiOnly = sharedPrefs.getBoolean("wifi_only", true);

        MainActivity activity = Robolectric.setupActivity(MainActivity.class);
        CheckBox box = (CheckBox) activity.findViewById(R.id.wifi_only);
        box.performClick();

        boolean isWifiOnlyNext = sharedPrefs.getBoolean("wifi_only", true);
        assertTrue(isWifiOnly == isWifiOnlyNext);

        CountDownLatch latch = new CountDownLatch(1);
        Observable.just(null)
                .delay(550L, TimeUnit.MILLISECONDS)
                .subscribe(nil -> {
                    boolean isWifiOnlyNext2 = sharedPrefs.getBoolean("wifi_only", true);
                    assertTrue(isWifiOnly != isWifiOnlyNext2);
                    latch.countDown();
                });
        try {
            latch.await(1L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

Service Testing

    public Observable<String> receiveCallState() {
        return RxBroadcastReceiver
                .fromBroadcast(LocalBroadcastManager.getInstance(this), new IntentFilter(ACTION_CALL_STATE))
                .map(intentWithContext -> intentWithContext.getIntent().getStringExtra(EXTRA_STATE))
                .observeOn(AndroidSchedulers.mainThread())
                .first();
    }


    public Observable<List<String>> startQuery(String number) {
        return JunkCallParser.queryPhoneNumber(number)
                .distinct(JunkCall::description)
                .map(JunkCall::description)
                .toList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

receiveCallState()

    @Test
    public void testReceiveCallState() {
        CountDownLatch latch = new CountDownLatch(1);
        TestSubscriber testSubscriber = new TestSubscriber<String>() {
            @Override
            public void onCompleted() {
                super.onCompleted();
                latch.countDown();
            }
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                latch.countDown();
            }
        };
        controller.get().receiveCallState()
                .subscribe(testSubscriber);
        LocalBroadcastManager instance = LocalBroadcastManager.getInstance(RuntimeEnvironment.application);
        ShadowLocalBroadcastManager mgr = shadowOf(instance);
        Intent intent = new Intent(JunkCallService.ACTION_CALL_STATE);
        intent.putExtra(JunkCallService.EXTRA_STATE, "test_state");
        mgr.sendBroadcast(intent);

        // Flush all UI tasks out of queue and force them to execute.
        Robolectric.flushForegroundThreadScheduler();
        Robolectric.getForegroundThreadScheduler().idleConstantly(true);
        try {
            latch.await(2L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        testSubscriber.assertNoErrors();
        testSubscriber.assertValue("test_state");
    }

startQuery()

@Test
    public void testStartQuery() {
        CountDownLatch latch = new CountDownLatch(1);
        controller.get().startQuery("0987352706")
                .subscribe(new Subscriber<List<String>>() {
                    @Override
                    public void onCompleted() {
                        latch.countDown();
                    }
                    @Override
                    public void onError(Throwable e) {
                        assertTrue(false);
                        latch.countDown();
                    }
                    @Override
                    public void onNext(List<String> strings) {
                        assertTrue(strings.size()>=2);
                    }
                });
        // Flush all worker tasks out of queue and force them to execute.
        Robolectric.flushBackgroundThreadScheduler();
        Robolectric.getBackgroundThreadScheduler().idleConstantly(true);
        // Flush all UI tasks out of queue and force them to execute.
        Robolectric.flushForegroundThreadScheduler();
        Robolectric.getForegroundThreadScheduler().idleConstantly(true);

        try {
            latch.await(5L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

NetworkUtil

    public static boolean isNetworkConnected(Context ctx) {
        ConnectivityManager mgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = mgr.getActiveNetworkInfo();
        return info != null && info.isConnected();
    }


//================================================================================================

    @Test
    public void isNetworkConnected() {
        ConnectivityManager mgr = (ConnectivityManager) RuntimeEnvironment.application.
                                                                                                                getSystemService(Context.CONNECTIVITY_SERVICE);
        ShadowConnectivityManager smgr = shadowOf(mgr);

        setActiveNetworkState(smgr, ConnectivityManager.TYPE_MOBILE, false);
        assertFalse(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application));

        setActiveNetworkState(smgr, ConnectivityManager.TYPE_MOBILE, true);
        assertTrue(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application));

        smgr.setActiveNetworkInfo(null);
        assertFalse(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application));
    }

NetworkUtil

    public static boolean isWifiConnected(Context ctx) {
        ConnectivityManager mgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = mgr.getActiveNetworkInfo();
        return info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI;
    }

//================================================================================================

    @Test
    public void isWifiConnected() {
        ConnectivityManager mgr = (ConnectivityManager) RuntimeEnvironment.application.
                                                                                                        getSystemService(Context.CONNECTIVITY_SERVICE);
        ShadowConnectivityManager smgr = shadowOf(mgr);
        setActiveNetworkState(smgr, ConnectivityManager.TYPE_MOBILE, false);

        assertFalse(NetworkUtil.isWifiConnected(RuntimeEnvironment.application));

        setActiveNetworkState(smgr, ConnectivityManager.TYPE_MOBILE, true);
        assertFalse(NetworkUtil.isWifiConnected(RuntimeEnvironment.application));

        setActiveNetworkState(smgr, ConnectivityManager.TYPE_WIFI, false);
        assertFalse(NetworkUtil.isWifiConnected(RuntimeEnvironment.application));

        setActiveNetworkState(smgr, ConnectivityManager.TYPE_WIFI, true);
        assertTrue(NetworkUtil.isWifiConnected(RuntimeEnvironment.application));

        smgr.setActiveNetworkInfo(null);
        assertFalse(NetworkUtil.isWifiConnected(RuntimeEnvironment.application));
    }

NetworkUtil

    public static boolean isWifiNetwork(Context ctx) {
        ConnectivityManager mgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = mgr.getActiveNetworkInfo();
        return info != null && info.getType() == ConnectivityManager.TYPE_WIFI;
    }
//================================================================================================
    @Test
    public void isWifiNetwork() {
        ConnectivityManager mgr = (ConnectivityManager) RuntimeEnvironment.application.getSystemService(Context.CONNECTIVITY_SERVICE);
        ShadowConnectivityManager smgr = shadowOf(mgr);

        setActiveNetworkState(smgr, ConnectivityManager.TYPE_MOBILE, true);
        assertFalse(NetworkUtil.isWifiNetwork(RuntimeEnvironment.application));

        setActiveNetworkState(smgr, ConnectivityManager.TYPE_WIFI, true);
        assertTrue(NetworkUtil.isWifiNetwork(RuntimeEnvironment.application));

        smgr.setActiveNetworkInfo(null);
        assertFalse(NetworkUtil.isWifiNetwork(RuntimeEnvironment.application));
    }

NetworkUtil

    public static boolean isNetworkConnected(Context ctx, boolean isWifiOnly) {
        if (isWifiOnly) {
            return isWifiConnected(ctx);
        } else {
            return isNetworkConnected(ctx);
        }
    }
//================================================================================================
    @Test
    public void isNetworkConnected2() {
        ConnectivityManager mgr = (ConnectivityManager) RuntimeEnvironment.application.getSystemService(Context.CONNECTIVITY_SERVICE);
        ShadowConnectivityManager smgr = shadowOf(mgr);
        setActiveNetworkState(smgr, ConnectivityManager.TYPE_MOBILE, true);
        assertTrue(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application, false));

        setActiveNetworkState(smgr, ConnectivityManager.TYPE_MOBILE, true);
        assertFalse(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application, true));

        setActiveNetworkState(smgr, ConnectivityManager.TYPE_WIFI, false);
        assertFalse(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application, true));

        setActiveNetworkState(smgr, ConnectivityManager.TYPE_WIFI, true);
        assertTrue(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application, true));

        smgr.setActiveNetworkInfo(null);
        assertFalse(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application, false));

        smgr.setActiveNetworkInfo(null);
        assertFalse(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application, true));
    }

NetworkUtil

    public static boolean isNetworkConnected(Context ctx, boolean isWifiOnly) {
        if (isWifiOnly) {
            return isWifiConnected(ctx);
        } else {
            return isNetworkConnected(ctx);
        }
    }
//================================================================================================
    @Test
    public void isNetworkConnected2() {
        ConnectivityManager mgr = (ConnectivityManager) RuntimeEnvironment.application.getSystemService(Context.CONNECTIVITY_SERVICE);
        ShadowConnectivityManager smgr = shadowOf(mgr);
        setActiveNetworkState(smgr, ConnectivityManager.TYPE_MOBILE, true);
        assertTrue(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application, false));

        setActiveNetworkState(smgr, ConnectivityManager.TYPE_MOBILE, true);
        assertFalse(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application, true));

        setActiveNetworkState(smgr, ConnectivityManager.TYPE_WIFI, false);
        assertFalse(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application, true));

        setActiveNetworkState(smgr, ConnectivityManager.TYPE_WIFI, true);
        assertTrue(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application, true));

        smgr.setActiveNetworkInfo(null);
        assertFalse(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application, false));

        smgr.setActiveNetworkInfo(null);
        assertFalse(NetworkUtil.isNetworkConnected(RuntimeEnvironment.application, true));
    }

deck

By Vincent SH

deck

  • 963