Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Kanunnikoff/139389d29a8631a6028ce095febaea61 to your computer and use it in GitHub Desktop.
Save Kanunnikoff/139389d29a8631a6028ce095febaea61 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment