lundi 16 novembre 2015

Why it keeps throwing NPE on mock object

I want to write a simple test that checks if user's data is shown on the UI.The Activity retrieves the data stored in sharedPreferences within onResume() and shows it on the UI.The following is my code for the test:

@RunWith(AndroidJUnit4.class)
public class EditProfileActivityTest {

@Mock
private UserPreference userPreference;
private String FAKE_NAME = "Test";

@Rule
public ActivityTestRule<EditProfileActivity> activityTestRule = new ActivityTestRule(EditProfileActivity.class,true,false);

@Before
public void setUp(){

    //Set fake SharedPreferences
    when(userPreference.getName()).thenReturn(FAKE_NAME);

    //Start Activity
    Intent intent = new Intent();
    activityTestRule.launchActivity(intent);
}

@Test
public void showUserData() throws Exception{
    onView(withId(R.id.name_tv)).check(matches(withText(FAKE_NAME)));
}
}  

where UserPreference is a custom class which simply wraps SharedPreference class and contains lots of getters and setters.This is its constructor

public UserPreference(Context context) {
    this.context = context;
    sharedPreferences = this.context.getSharedPreferences("Pref", Context.MODE_PRIVATE);
    prefEditor = sharedPreferences.edit();
}  

and one of its getter

public String getName() {
    return sharedPreferences.getString(context.getString(R.string.pref_name), "Guest");
}  

But when I run the test,it keeps showing NullPointerExceptiions on this line

when(userPreference.getName()).thenReturn(FAKE_NAME);

I've searched for related topics but I still can't see why.I think the concept of mock is to re-define a method's behavior no matter what the real implementation is. I am new to testing,so I am sorry in advance if this is a silly qustion.

Aucun commentaire:

Enregistrer un commentaire