模拟方法仍在执行中

时间:2018-03-15 06:47:42

标签: android mockito powermock

我在Android代码库中运行此测试。我的目标方法依赖于另一种检查网络连接的方法。由于网络连接检查具有Android依赖性,我试图模拟该方法。不过,它正在执行,我正在使用正在使用Android上下文方法的NPE。我曾尝试过Roboelectric和Junit跑步者。

import android.content.Context;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;


@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
@PrepareForTest({Network.class, Messages.class})
public class MessagesTest {

    @Test
    public void getStatus() throws Exception {
        PowerMockito.mockStatic(Network.class);
        when(Network.isConnected(any(Context.class))).thenReturn(false);
        String s = Messages.getStatus(mock(Context.class));
        assertEquals(s, "offline");
    }

}




public class Messages {

    public static String getStatus(Context context){
        if(Network.isConnected(context)) return "online";
        else return "offline";
    }
}



public class Network {

    private static final String MOBILE = "MOBILE";
    private static final String WIFI = "WIFI";


    public static boolean isConnected(Context context) {
        boolean isWifiConnected = false;
        boolean isMobileConnected = false;

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] allNetworkInfo = connectivityManager.getAllNetworkInfo();
        for (NetworkInfo networkInfo : allNetworkInfo) {
            if (networkInfo != null && WIFI.equalsIgnoreCase(networkInfo.getTypeName())) {
                isWifiConnected = networkInfo.isConnectedOrConnecting();
            }

            if (networkInfo != null && MOBILE.equalsIgnoreCase(networkInfo.getTypeName())) {
                isMobileConnected = networkInfo.isConnectedOrConnecting();
            }

        }
        return isWifiConnected || isMobileConnected;
    }
}

Network类中抛出NPE,其中context.getSystemService()被调用。

1 个答案:

答案 0 :(得分:0)

看起来我只需要PowerMockRunner而不是RobolectricTestRunner。如果使用RobolectricTestRunner,那么我们还应添加以下内容:

@Rule
public PowerMockRule powerMockRule = new PowerMockRule();

@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();