使用Mockito进行NPE单元测试

时间:2018-10-04 03:31:50

标签: 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();
}
}

这是测试班

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

@Test
public void isEmailValidTest1() {
    Assert.assertTrue(isEmailValid(DUMMY_EMAIL));
}
}

此行中出现空指针异常

return Patterns.EMAIL_ADDRESS.matcher(email).matches();

这是堆栈跟踪

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

有人可以帮我解决这个问题吗?谢谢

5 个答案:

答案 0 :(得分:1)

只需将其从Patterns.EMAIL_ADRESS.matcher()切换为PatternsCompat.EMAIL_ADRESS.matcher()即可解决。比它应该起作用。

答案 1 :(得分:0)

您是否检查了:

的结果
 Matcher m = Patterns.EMAIL_ADDRESS.matcher(email);

答案 2 :(得分:0)

认为它应该匹配:

public static boolean isEmailValid(String email) {
    Pattern pattern = Pattern.compile(Patterns.EMAIL_ADDRESS);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}

答案 3 :(得分:0)

我正在获得NPE,因为在单元测试中Patterns.EMAIL_ADDRESS为空。切换到android.support.v4.util.PatternsCompat解决了该问题

答案 4 :(得分:0)

您应该获得预期的输出,而不是模拟模式。

建议使用Robolectric

代码段如下:

dicts = [{1: 'a'}, {2: 'b'}, {3: 'c'}]
merged = {k: v for d in dicts for k, v in d.items()}
print(merged)  # {1: 'a', 2: 'b', 3: 'c'}