Skip to content

Instantly share code, notes, and snippets.

@IvanShafran
IvanShafran / shared-preferences-mock-sample.java
Last active June 29, 2019 20:19
Shared preferences mock sample
public class CounterPreferences {
// ...
private final SharedPreferences sharedPreferences;
public CounterPreferences(@NonNull final Context context) {
sharedPreferences = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
}
public int getCounter() {
return sharedPreferences.getInt(KEY, 0);
}
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
testImplementation 'com.github.IvanShafran:shared-preferences-mock:1.0'
}
class BuyPreferencesImpl(context: Context) : BuyPreferences {
companion object {
private val PREFERENCES_FILENAME = "BUY_PREFERENCES"
private val BUY_COUNT_KEY = "BUY_COUNT_KEY"
}
private val sharedPreferences = context.getSharedPreferences(
PREFERENCES_FILENAME,
Context.MODE_PRIVATE
)
interface BuyPreferences {
fun incrementBuyCount()
fun getBuyCount(): Int
}
class BuyPreferencesImpl(context: Context) : BuyPreferences {
// ...
private val sharedPreferences: SharedPreferences = context.getSharedPreferences(...)
override fun incrementBuyCount() {
interface Time {
fun getCurrentTimeMillis(): Long
}
class TimeImpl : Time {
override fun getCurrentTimeMillis() = System.currentTimeMillis()
}
class ShowRateUsLogic(
private val rateUsPreferences: RateUsPreferences,
private val buyPreferences: BuyPreferences,
private val time: Time
) {
fun shouldShowRateUs(): Boolean {
val timeFromLastShown = time.getCurrentTimeMillis() - rateUsPreferences.getLastShownTimeMillis()
return when {
// User doesn't want to see "rate us" again
rateUsPreferences.isNeverShownAgainClicked() -> false
public class BuyPreferencesMock implements BuyPreferences {
private int count;
@Override public void incrementBuyCount() {
++count;
}
@Override public int getBuyCount() {
return count;
}
public class ShowRateUsLogicTest {
private RateUsPreferencesMock rateUsPreferences;
private BuyPreferencesMock buyPreferences;
private TimeMock time;
private ShowRateUsLogic showRateUsLogic;
@Test public void test1() {
rateUsPreferences = new RateUsPreferencesMock();
buyPreferences = new BuyPreferencesMock();
time = new TimeMock();
class ShowRateUsLogicTest {
// property declaration and setup are skipped
private fun prepareConditions(
buyClickedTimes: Int = 0,
isNeverShownAgainClicked: Boolean = false,
isRateNowClicked: Boolean = false,
lastShownTimeMillis: Long = 0,
currentTimeMillis: Long = 0
) {
repeat(buyClickedTimes) { buyPreferences.incrementBuyCount() }