Unit test Android, getString from resource

前端 未结 3 1717
既然无缘
既然无缘 2021-02-12 09:59

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

相关标签:
3条回答
  • 2021-02-12 10:20

    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.

    0 讨论(0)
  • 2021-02-12 10:23

    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.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.

    0 讨论(0)
  • 2021-02-12 10:24

    Untested: would it work to use the below, and probably targetContext?

    android {
       testOptions {
         unitTests {
            includeAndroidResources = true
         }
      }
    }
    
    0 讨论(0)
提交回复
热议问题