I have just read about Unit Instrumented Testing in Android and I wonder how I can mock a SharedPreferences without any SharedPreferencesHelper class on it like here
There is a better way to mock SharedPreferences, IMHO. I like Mockito, but it is unproductive to mock SharedPreferences in every test.
Luckily, we can use the shared-preferences-mock library. This library implements SharedPrefences on JVM, so it behaves like a real class. Moreover, it is possible to write local unit tests.
For your case:
import com.github.ivanshafran.sharedpreferencesmock.SPMockBuilder;
class Test {
private Context context;
private SharedPreferences sharedPreferences;
@Before
public void setUp() {
this.sharedPreferences = new SPMockBuilder().createSharedPreferences();
this.context = Mockito.mock(Context.class);
Mockito.when(context.getSharedPreferences(Constants.LOGGED_USER_PREFERENCES,0))
.thenReturn(sharedPreferences);
}
@Test
public void test() {
sharedPreferences.edit().putString(Constants.LOGGED_USERNAME, "admin").commit();
String value = Auth.getLoggedUser(context);
asssertEquals("admin", value);
}
}
Add it to your root build.gradle at the end of repositories:
allprojects {
repositories {
maven { url 'https://jitpack.io' }
}
}
Add the dependency:
dependencies {
testImplementation 'com.github.IvanShafran:shared-preferences-mock:1.0'
}