我想用Android提供的一些代码验证电子邮件.
这是我要模拟的代码:
if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
throw new InvalidPhoneException(phone);
在我的测试文件中:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Patterns.class })
public class UserTest {
@Before
public void mockValidator() {
mockStatic(Patterns.class);
when(Patterns.EMAIL_ADDRESS.matcher(any(String.class)).matches()).thenReturn(true);
}
启动测试时出现此错误:
java.lang.NullPointerException
at ch.mycompany.myapp.model.UserTest.mockValidator(UserTest.java:59)
编辑1:
我试过了 :
mockStatic(Patterns.class);
Field field = PowerMockito.field(Patterns.class, "EMAIL_ADDRESS");
field.set(Patterns.class, mock(Pattern.class));
// prepare matcher
Matcher matcher = mock(Matcher.class);
when(matcher.matches())
.thenReturn(true);
// final mock
when(Patterns.EMAIL_ADDRESS.matcher(any(String.class)))
.thenReturn(matcher);
但是当我这样做时,我的代码(Patterns.EMAIL_ADDRESS.matcher(email).matches())
返回始终为假.这很混乱.
解决方法:
您正在验证电子邮件字段
您不会在此处嘲笑何时返回true或false的行为.还请注意,我们无法模拟最终课程(模式).
当正则表达式模式与值匹配时,它返回true或false
而不是使事情复杂化.只需通过传递值来执行评估.
解决方案1:
@Test
public void test() throws Exception{
String email="hello@gmail.com";
System.out.println(Patterns.EMAIL_ADDRESS.matcher(email).matches());
}
protected static class Patterns{
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private static final Pattern EMAIL_ADDRESS=Pattern.compile(EMAIL_PATTERN);
}
output :
true
解决方案2:模拟Matcher行为以返回true或false
@RunWith(PowerMockRunner.class)
@PrepareForTest({Pattern.class,Matcher.class})
public class TestEmailPattern {
@Test
public void test() throws Exception{
String email="hello@gmail.com";
Pattern pattern=PowerMockito.mock(Pattern.class);
Matcher matcher=PowerMockito.mock(Matcher.class);
PowerMockito.when(matcher.matches()).thenReturn(true);
assertEquals(Patterns.EMAIL_ADDRESS.matcher(email).matches(),true);
}
protected static class Patterns{
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private static final Pattern EMAIL_ADDRESS=Pattern.compile(EMAIL_PATTERN);
}
}