Unit test Android, getString from resource

I am trying to do a unit test for an Android app, and I need to get a string from res.string resources. The class I want to test is a POJO class. I make an application in two languages, because of this I need to get a string from a resource. The problem is that I cannot get context or activity, maybe? I know that with the Instrumentation test I can do this, but I need to check some functions (white box test) before doing a control test (black box test). This is the function I should check:

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); } 

An attempt to execute context.getResources().getString(R.string.sInicialLunes))

If I put 'Mon' instead of context.getResources().getString(R.string.sInicialLunes)) or 'L', it works fine, is it possible to get context or activity to access the resource folder?

I am testing Mockito, and the setUp function:

 @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); mContext = Mockito.mock(Alerta.class); Mockito.when(mContext.getApplicationContext()).thenReturn(mContext); alertaPOJO = new AlertaPOJO(); } 

thanks

+7
android junit testing mockito
source share
2 answers

If you use Context only to get the String resource, I would just make fun of only the getResources().getString() (see JUnit4 note):

 @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.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 importantly, they work faster.

+7
source share

You have no real android context when you use the JVM unit test. In your case, perhaps you can try Android Instrumentation Test, as a rule, it is implemented in the "androidTest" directory of your project.

+3
source share

All Articles