本文介绍了用Mockito模拟android模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用Android提供的一些代码验证电子邮件。
I want validate an email with some code provided by 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);
}
启动测试时出现此错误:
I got this error when I launch the tests :
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() )
返回值始终为false。
But when I do that, my code (Patterns.EMAIL_ADDRESS.matcher(email).matches())return always false. This is confusing.
推荐答案
使用可以在这种情况下为您省去很多麻烦。
Using Robolectric will save you lot of headaches in this kind of situation.
这篇关于用Mockito模拟android模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!