使用Mockito进行NPE单元测试

man*_*ool 1 java android unit-testing mockito

我试图对下面的一些util类进行单元测试:

public final class WalletInputValidationUtils {
private WalletInputValidationUtils() {
}

public static boolean isEmailValid(CharSequence email) {
    return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
}
Run Code Online (Sandbox Code Playgroud)

这是测试班

@RunWith(PowerMockRunner.class)
public class WalletInputValidationUtilsTest {
private static final CharSequence DUMMY_EMAIL = "email@gmail.com";

@Test
public void isEmailValidTest1() {
    Assert.assertTrue(isEmailValid(DUMMY_EMAIL));
}
}
Run Code Online (Sandbox Code Playgroud)

我在这行有空指针异常

return Patterns.EMAIL_ADDRESS.matcher(email).matches();
Run Code Online (Sandbox Code Playgroud)

这是堆栈跟踪

java.lang.NullPointerException
at kudo.mobile.app.wallet.backwardcompatibility.WalletInputValidationUtils.isEmailValid(WalletInputValidationUtils.java:14)
at kudo.mobile.app.wallet.backwardcompatibility.WalletInputValidationUtilsTest.isEmailValidTest(WalletInputValidationUtilsTest.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:316)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:300)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunne
Run Code Online (Sandbox Code Playgroud)

谁能帮我解决这个问题?谢谢

Man*_*lva 6

刚从切换到Patterns.EMAIL_ADRESS.matcher()即可解决PatternsCompat.EMAIL_ADRESS.matcher()。那应该工作。