androidunit-testingmockitopowermockito

Mock android Patterns with mockito


I want validate an email with some code provided by Android.

Here is the code I want to mock :

 if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
      throw new InvalidPhoneException(phone);

In my test file :

@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)

EDIT 1 :

I tried :

    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);

But when I do that, my code (Patterns.EMAIL_ADDRESS.matcher(email).matches()) return always false. This is confusing.


Solution

  • Using Robolectric will save you lot of headaches in this kind of situation.