Skip to content

Instantly share code, notes, and snippets.

@marcouberti
Last active March 10, 2021 16:57
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save marcouberti/500621c4646f5fdb8d69721d5186cac3 to your computer and use it in GitHub Desktop.
Save marcouberti/500621c4646f5fdb8d69721d5186cac3 to your computer and use it in GitHub Desktop.
Mock Android Context using Mockito
import org.mockito.Mock;
import static org.mockito.Mockito.when;
@Mock
private Context mockApplicationContext;
@Mock
private Resources mockContextResources;
@Mock
private SharedPreferences mockSharedPreferences;
@Before
public void setupTests() {
// Mockito has a very convenient way to inject mocks by using the @Mock annotation. To
// inject the mocks in the test the initMocks method needs to be called.
MockitoAnnotations.initMocks(this);
// During unit testing sometimes test fails because of your methods
// are using the app Context to retrieve resources, but during unit test the Context is null
// so we can mock it.
when(mockApplicationContext.getResources()).thenReturn(mockContextResources);
when(mockApplicationContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mockSharedPreferences);
when(mockContextResources.getString(anyInt())).thenReturn("mocked string");
when(mockContextResources.getStringArray(anyInt())).thenReturn(new String[]{"mocked string 1", "mocked string 2"});
when(mockContextResources.getColor(anyInt())).thenReturn(Color.BLACK);
when(mockContextResources.getBoolean(anyInt())).thenReturn(false);
when(mockContextResources.getDimension(anyInt())).thenReturn(100f);
when(mockContextResources.getIntArray(anyInt())).thenReturn(new int[]{1,2,3});
// here you can mock additional methods ...
// if you have a custom Application class, you can inject the mock context like this
MyCustomApplication.setAppContext(mockApplicationContext);
}
@alexmelyon
Copy link

alexmelyon commented Aug 8, 2019

Please add mock
when(mockApplicationContext.getApplicationContext()).thenReturn(mockApplicationContext);

@NelzkieCoder
Copy link

Can you mock a getString with placeHolder?

@l225li
Copy link

l225li commented Mar 15, 2020

Could you give example of MyCustomApplication please?

@marcouberti
Copy link
Author

marcouberti commented Mar 16, 2020

Could you give example of MyCustomApplication please?

@l225li MyCustomApplication is simply an Application subclass like this (in Kotlin):

class TDFApplication : Application() { override fun onCreate(){} }

remember to declare your custom application class into the Manifest.xml file like this:

<manifest> ... <application android:name=".MyCustomApplication"> ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment