Search code examples
androidandroid-wifirobolectric

Robolectric: failed on start test cause of wifi start scan


I've created a little test under Robolectric. Unfortunately, I must comment these lines for having success test :

public class MyApplication extends Application {

private void setupApplication() {

....

//mNetworkEvents = new NetworkEvents(this, EventBus.getDefault())
//            .withPingUrl(BuildConfig.PING_SERVER_URL)
//            .withPingTimeout(BuildConfig.PING_TIMEOUT);

}

This class "NetworkEvents" allows to test internet connectivity. And in this class there is this call:

public static void startWifiScan(Context context) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    wifiManager.startScan();
}

And the problem is the start wifi scan...

This is error:

java.lang.NullPointerException at android.net.wifi.WifiManager.startScan(WifiManager.java:995)

How can I do run my test without comment these line in my application class ??

Thanks guys!


Solution

  • I've tried to reproduce error and found same. I was thinking that you should first set WifiManager to start using it. However problem is deeper.

    Robolectric has shadow class for WifiManager and it is returned to you but startScan() method is not shadowed and is trying to call real class from Android. If you take a look to sources there is service field, the implementation of WiFi details, in real class and that is null when running with Robolectric.

    I created issue on the Robolectric github https://github.com/robolectric/robolectric/issues/1969