can wifi be switched on/off in test case through robotium

ε祈祈猫儿з 提交于 2019-12-05 04:35:07

Yes you can do it, see the example:

public void testNoNetworkConnection() throws Exception {

    setWifiEnabled(false);

    // do stuff solo.something

   setWifiEnabled(true);

}

private void setWifiEnabled(boolean state) {
    WifiManager wifiManager = (WifiManager)solo.getCurrentActivity().getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(state);
}

Remember to add permission in your Manifest file:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

EDIT: With the new Robotium 5.3.1 you can use setWiFiData(Boolean turnedOn) to turn wifi on or off (See documentation)

Enjoy

You can use ExtSolo provided by Testdroid. Library can be found on https://github.com/bitbar/robotium-extensions and api for needed method: turn wifi. If you don't want to use extra library you can use code as below:

protected void turnWifi(boolean enabled) {
    try {
        WifiManager wifiManager = (WifiManager) getInstrumentation()
                .getTargetContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(enabled);
    } catch (Exception ignored) {
        // don't interrupt test execution, if there
        // is no permission for that action
    }
}

You need permission in your application to change state of Wifi

Since, you will test the application where you know the behavior(when wifi is on and when wifi is off) of application , you can mock the data accordingly. Mocking the data will make the application to behave as it is expected in that particular situation.

There is not an easy way to do this, that is different to me saying that it is not possible though but might be enough to disuade you from doing this.

If your application has the correct permissions then you can from your robotium script in fact turn on or off the wifi just as any application can. But remember the permission needs to be in your applications manifest not your test apk manifest.

If your application doesn't have the correct permission (and you are unwilling to change it) there is another way but is quite a lot of work (working on getting the solution I use open sourced). Make an application that does have the permission as a service, bind to that service in your tests and ask that service to turn off the wifi.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!