3

使用 Android 并在设备上进行测试,我使用它来检查 WiFI 是否已连接:

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

效果很好。有没有办法为 JUnit 模拟这个?

提前谢谢,马库斯

4

1 回答 1

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() {..}
}
于 2012-08-11T07:44:05.817 回答