【发布时间】:2017-05-21 22:55:45
【问题描述】:
我想使用 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()) 返回总是假的。这令人困惑。
【问题讨论】:
-
尝试使用 Roboelectric 解决它。 stackoverflow.com/questions/52638565/…
标签: android unit-testing mockito powermockito