jeudi 18 mai 2017

Testing method which access static final field locally inside method gives error

I am new to testing and i have this problem while testing the below code gives null pointer exception.

This is my class of CommonFunctions which contains method for email validation

Source file ----->

import android.util.Patterns;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonFunctions {

   private Context context;

   public CommonFunctions(Context context) {
      this.context = context;
    }


   //to check whether email is valid or not

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

 }

The "Patterns.EMAIL_ADDRESS" is from android.util.Patterns EMAIL_ADDRESS is static final field


My Testing code using Junit and Mockito

   import android.content.Context;

   import org.junit.Test;
   import org.junit.runner.RunWith;
   import org.mockito.Mock;
   import org.mockito.runners.MockitoJUnitRunner;

   import static org.hamcrest.CoreMatchers.is;
   import static org.junit.Assert.*;


    @RunWith(MockitoJUnitRunner.class)
    public class CommonFunctionsTest {

    @Mock
    Context mMockContext;


    @Test
    public void isEmailValid() throws Exception {

       CommonFunctions commonFunctions = new CommonFunctions(mMockContext);
        assertThat(commonFunctions.isEmailValid("name@gmail.com"), is(true));

    }

}

Error : java.lang.NullPointerException at this line:

Matcher matcher = pattern.matcher(email);

in the isEmailValid method of CommonFunction class

the 'pattern' is still null

that means while testing it I can not access the "Patterns.EMAIL_ADDRESS" from the android.util.Patterns, EMAIL_ADDRESS is static final field

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire