如何在JUNIT中模拟WiFi连接?

时间:2012-08-11 06:35:47

标签: android junit mocking wifi

在设备上使用Android和测试,如果连接了WiFI,我会用它来检查:

        ConnectivityManager manager = (ConnectivityManager) MyApplication.getMyApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    return info.isConnectedOrConnecting();

运作良好。有没有办法为JUnit模拟这个?

Thanx提前, 马库斯

1 个答案:

答案 0 :(得分:0)

如果将代码移动到自己的WifiServiceClass并让应用程序依赖于接口,则可以模拟此功能:

public class MyClassThatRequiresWifi {
    private IWifiService wifiService;
    public MyClassThatRequiresWifi(IWifiService wifiService) {
        this.wifiService = wifiService;
    }

    public void someMethodThatNeedsWifi() {
        if (this.wifiService.isConnectedOrConnecting())
            ...
    }
}

public IWifiService {
    boolean isConnectedOrConnecting();
}

public WifiService implements IWifiService {
    boolean isConnectedOrConnecting() {..}
}