Accessing resources in an android test project

后端 未结 4 1158
天涯浪人
天涯浪人 2020-12-06 10:06

I have setup an android test project that runs junit tests. It\'s using two eclipse projects \"Application\" and \"ApplicationTest\" where my tests are in the \"ApplicationT

相关标签:
4条回答
  • 2020-12-06 10:06

    With build tools 3.0.0 you can use ActivityTestRule

    @RunWith(AndroidJUnit4::class)
    @SmallTest
    class MainActivityTest {
        @Rule
        @JvmField
        var mainActivityRule = ActivityTestRule(MainActivity::class.java)
    
        private val baseUrl: String
            get() {
                return mainActivityRule.activity.getString(R.string.base_url)
            }
    
        @Test
        fun launchingWithMovieIntent() {
                assert.that(baseUrl, equalTo("someValue")
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-06 10:18

    I would suggest extending ActivityTestCase instead of AndroidTestCase. You can than access test project resources via

    getInstrumentation().getContext().getResources().openRawResource(R.raw.your_res).

    Dummy test case example:

    public class Test extends ActivityTestCase {
    
       public void testFoo() {  
    
          // .. test project environment
          Context testContext = getInstrumentation().getContext();
          Resources testRes = testContext.getResources();
          InputStream ts = testRes.openRawResource(R.raw.your_res);
    
          assertNotNull(testRes);
       }    
    }
    

    And then in test methods use getInstrumentation().getTargetContext() wherever you used getContext() in your AndroidTestCase extension.

    0 讨论(0)
  • 2020-12-06 10:24

    Since Android Gradle Plugin version 1.1 you haven't to use Instrumentation to load file resource.

    I wrote here how to do it with POJO unit test case.

    0 讨论(0)
  • 2020-12-06 10:27

    I derived the test case as follows:

    class MyTest extends InstrumentationTestCase {
        void setUp() {
            InputStream is = getInstrumentation().getContext().getAssets()
                .open("test_image.bmp");
            ...
       }
    }
    

    And the file test_image.bmp is saved in assets directory, which is reasonable if you intend to use the asset for some testing related work - and its not part of ui resources. The technique is used in another context here: https://stackoverflow.com/a/4570206/1577626

    0 讨论(0)
提交回复
热议问题