Unit test Android, getString from resource
Solution 1
If you are using Context
only for obtaining String
resource, I would go by mocking only getResources().getString()
part like this (see JUnit4 notation):
@RunWith(MockitoJUnitRunner.class)
public class AlertaPOJOTest {
@Mock
Context mMockContext;
@Test
public void setDiaByTextView() {
String texto = "L,M,X,J,V,S,D";
when(mMockContext.getString(R.string.sInicialLunes))
.thenReturn(INITIAL_LUNES);
alertaPOJO.setDiaByText(texto);
assertEquals(alertaPOJO.getIsSelectedArray()[0], true);
assertEquals(alertaPOJO.getI_idiaSeleccionado()[0], 1);
}
}
There are many reasons to stay with JVM tests, most important one, they are running quicker.
Solution 2
You don't have a real android Context while you are using JVM unit test. For your case, maybe you can try Android Instrumentation Test, typically it is implemented in the "androidTest" directory of your project.
Solution 3
Untested: would it work to use the below, and probably targetContext?
android {
testOptions {
unitTests {
includeAndroidResources = true
}
}
}
Huan
Updated on October 20, 2021Comments
-
Huan over 2 years
I am trying to do an unit test for an android app and I need to get a string from res.string resources. The class that I want to test is a POJO class. I am doing the app in two languages, due to this, I need to get a string from resource. The problem is that I cannot get the context or the activity, is possible? I know that with Instrumentation test I can do it, but I need to test some functions (white box test) before to do the instrumentation test (black box test). This is the function that I have to test:
public void setDiaByText(String textView) { getll_diaSeleccionado().clear(); if (textView.contains(context.getResources().getString(R.string.sInicialLunes))) { getll_diaSeleccionado().add(0); getIsSelectedArray()[0] = true; getI_idiaSeleccionado()[0] =1; } else { getIsSelectedArray()[0] = false; getI_idiaSeleccionado()[0] =0; } }
And this is the test:
@Test public void setDiaByTextView() { String texto = "L,M,X,J,V,S,D"; alertaPOJO.setDiaByText(texto); assertEquals(alertaPOJO.getIsSelectedArray()[0], true); assertEquals(alertaPOJO.getI_idiaSeleccionado()[0], 1); }
It crash when try to do
context.getResources().getString(R.string.sInicialLunes))
If I put 'Mon' instead of
context.getResources().getString(R.string.sInicialLunes))
or 'L' it work perfectly so, is possible to get the context or the activity in order to access to resource folder?I am testing with Mockito and the setUp function is:
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); mContext = Mockito.mock(Alerta.class); Mockito.when(mContext.getApplicationContext()).thenReturn(mContext); alertaPOJO = new AlertaPOJO(); }
Thanks