Last active
May 2, 2024 11:43
-
-
Save marcouberti/500621c4646f5fdb8d69721d5186cac3 to your computer and use it in GitHub Desktop.
Mock Android Context using Mockito
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Can you mock a getString with placeHolder?
Could you give example of MyCustomApplication
please?
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"> ...
Thank you @marcouberti!
A depracation note on initMocks
:
@deprecated public static void initMocks (Object testClass) Deprecated.
Use openMocks(Object) instead.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please add mock
when(mockApplicationContext.getApplicationContext()).thenReturn(mockApplicationContext);