Issue
I am trying to mock a simple shared preferences using Mockito . Since, the examples on google are too complicated to make anything out of it, I decided to go ahead on my own. The shared preferences are setup using dagger. It crashes with NPE in the saveString method in the SharedPreferenceManager class on the putString line.
@Module
public class StudentModule {
@Provides
@Singleton
static Context getContext(Application application) {
return application.getApplicationContext();
}
@Provides
@Singleton
static SharedPreferences getSharedPreferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
}
There is a manager class:
public class SharedPreferenceManager {
private SharedPreferences sharedPreferences;
private Context context;
@Inject public SharedPreferenceManager(SharedPreferences sharedPreferences, Context context){
this.sharedPreferences=sharedPreferences;
this.context=context;
}
public String doSomething(){
return sharedPreferences.getString("s","");
}
public void saveString(String s){
System.out.println(sharedPreferences.getClass().getSimpleName());
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("s","bis").apply();
}
}
Here is the test:
@RunWith(MockitoJUnitRunner.class)
public class MockTest {
@InjectMocks
SharedPreferenceManager sharedPreferenceManager;
@Mock SharedPreferences sharedPreferences;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void isSharedPefWorking(){
sharedPreferenceManager.saveString("bis");
assertEquals("bis",sharedPreferenceManager.doSomething());
}
}
Solution
SharedPreferences
uses a SharedPreferences.Editor
which you're not currently mocking.
You would need to do something like the following to mock and verify the behaviour of your SharedPreferenceManager
.
@RunWith(MockitoJUnitRunner.class)
public class MockTest {
@InjectMocks
SharedPreferenceManager sharedPreferenceManager;
@Mock
SharedPreferences sharedPreferences;
@Mock
SharedPreferences.Editor sharedPreferencesEditor;
final String savedString = "savedString";
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
when(sharedPreferences.edit()).thenReturn(sharedPreferencesEditor);
when(sharedPreferencesEditor.putString(anyString(), anyString())).thenReturn(sharedPreferencesEditor);
}
@Test
public void saveString() {
sharedPreferenceManager.saveString(savedString);
verify(sharedPreferencesEditor).putString("s", savedString);
}
@Test
public void getString() {
when(sharedPreferences.getString("s","")).thenReturn(savedString);
String preferenceString = sharedPreferenceManager.doSomething();
assertEquals(preferenceString, savedString);
}
}
Answered By - Chris
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.