Mockito: How to use getString with mockito?

I used a Google example on how to check the code SharedPreferenceshere by creating a class SharedPreferencesHelper:

https://github.com/googlesamples/android-https://github.com/googlesamples/android-testing/blob/master/unit/BasicSample/app/src/main/java/com/example/android/testing/ unittesting / BasicSample / SharedPreferencesHelper.java

You can see that the class uses real strings hardcoded in the class, like the keys to SharedPreferences- here is an excerpt from the class:

public class SharedPreferencesHelper {

    // Keys for saving values in SharedPreferences.
    static final String KEY_NAME = "key_name";
    static final String KEY_DOB = "key_dob_millis";
    static final String KEY_EMAIL = "key_email";

    public boolean savePersonalInfo(SharedPreferenceEntry sharedPreferenceEntry){
        // Start a SharedPreferences transaction.
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString(KEY_NAME, sharedPreferenceEntry.getName());
        editor.putLong(KEY_DOB, sharedPreferenceEntry.getDateOfBirth().getTimeInMillis());
        editor.putString(KEY_EMAIL, sharedPreferenceEntry.getEmail());

        // Commit changes to SharedPreferences.
        return editor.commit();
    }

When testing this when using the class SharedPreferencesHelperTesthere, they access mocked SharedPreferencesusing the same variables that are defined in the above class:

https://github.com/googlesamples/android-testing/blob/master/unit/BasicSample/app/src/test/java/com/example/android/testing/unittesting/BasicSample/SharedPreferencesHelperTest.java

:

when(mMockSharedPreferences.getString(eq(SharedPreferencesHelper.KEY_NAME), anyString()))
            .thenReturn(mSharedPreferenceEntry.getName());
    when(mMockSharedPreferences.getString(eq(SharedPreferencesHelper.KEY_EMAIL), anyString()))
            .thenReturn(mSharedPreferenceEntry.getEmail());
    when(mMockSharedPreferences.getLong(eq(SharedPreferencesHelper.KEY_DOB), anyLong()))
            .thenReturn(mSharedPreferenceEntry.getDateOfBirth().getTimeInMillis());

Google, context, string.xml SharedPreferences, , , , getString(), :

mSharedPreferences.getString(context.getString(R.string.name),"");

, , context.getString , , mockito :

Mockito - ,

mockito unit test getString? getString , unit test .

, SharedPreferences, SharedPreferences, getStrings:

public class SharedPreferencesHelper {

    // The injected SharedPreferences implementation to use for persistence.
    private final SharedPreferences mSharedPreferences;
    private Context context;

    public SharedPreferencesHelper(SharedPreferences sharedPreferences, Context context) {
        mSharedPreferences = sharedPreferences;
        this.context = context;
    }

    public boolean saveName(String name) {
        // Start a SharedPreferences transaction.
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString(context.getString(R.string.name), name);
        return editor.commit();
    }

    public String fetchName() {
        // Start a SharedPreferences transaction.
        return mSharedPreferences.getString(context.getString(R.string.name),"");
    }

    public boolean saveGender(String gender) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString(context.getString(R.string.gender), gender);
        return editor.commit();
    }

}

, - google SharedPreferencesHelperTest:

@RunWith(MockitoJUnitRunner.class)
public class SharedPreferencesHelperTest {

    private static final String TEST_NAME = "Test name";

    private SharedPreferencesHelper mMockSharedPreferencesHelper;

    @Mock
    SharedPreferences mMockSharedPreferences;
    @Mock
    SharedPreferences.Editor mMockEditor;
    @Mock
    MockContext context;

    @Before
    public void setUp() throws Exception {
        // Create a mocked SharedPreferences.
        mMockSharedPreferencesHelper = createMockSharedPreference();
    }

    @Test
    public void testSaveName() throws Exception {
        boolean success = mMockSharedPreferencesHelper.saveName(TEST_NAME);
        Timber.e("success " + success);
        assertThat("Checking that name was saved... returns true = " + success,
                success, is(true));
        String name = mMockSharedPreferencesHelper.fetchName();
        Timber.e("name " + name);
        assertThat("Checking that name has been persisted and read correctly " + name,
                TEST_NAME,
                is(name));
    }

    /**
     * Creates a mocked SharedPreferences.
     */
    private SharedPreferencesHelper createMockSharedPreference() {
        // Mocking reading the SharedPreferences as if mMockSharedPreferences was previously written
        // correctly.
        when(mMockSharedPreferences.getString(Matchers.eq("name"), anyString()))
                .thenReturn(TEST_NAME);
        when(mMockSharedPreferences.getString(Matchers.eq("gender"), anyString()))
                .thenReturn("M");
        // Mocking a successful commit.
        when(mMockEditor.commit()).thenReturn(true);
        // Return the MockEditor when requesting it.
        when(mMockSharedPreferences.edit()).thenReturn(mMockEditor);
        return new SharedPreferencesHelper(mMockSharedPreferences, context);
    }
}

, getString SharedPreferencesHelper. , , ..:

public String fetchName() {
    // Start a SharedPreferences transaction.
    return mSharedPreferences.getString("name","");
}

, ?

+4
2

2017.06 :

jbarat, Robolectric. , , /// Robolectric/Android Studio.

, , , Android Studio 2.3.3 Robolectric 3.3.2:

build.gradle:

testCompile "org.robolectric:robolectric:3.3.2"
testCompile "org.robolectric:shadows-multidex:3.3.2"

MyClass.java:

public static String myGetString(Context context) {
    return context.getString(R.string.my_string);
}

:

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, packageName = "com.myapplication", sdk = 19)
public class MyTest {
    private Context mockContext;

    @Before
    public void setUp() {
        // inject context provided by Robolectric
        mockContext = RuntimeEnvironment.application.getApplicationContext();
    }

    @Test
    public void test_myGetString() {
        assertEquals("MY STRING", MyClass.myGetString(mockContext));
    }
}
+2

All Articles