Search code examples
androidunit-testingfile-listing

Access image in my Android Tests


I am working on an Android app. It has corresponding spec/test application. As part of some of my tests, I need to pick up an image from my assets folder and calculate SHA-1 for it. I can calculate SHA, as long as I can pick the image. Since the tests run on emulator; I am not sure how to pick the image in my test.

Does anyone have any idea, how I can go about it. With and without AssetManager maybe? Any ideas will be helpful.

Cheers -Priyank


Solution

  • I do this by extending ActivityInstrumentationTestCase2, then in the setup getting a reference to the activity and finally getting the AssetManager.

        public class Sha1Test
            extends ActivityInstrumentationTestCase2<MyActivity> {
            private AssetManager m_assetManager;
            public Sha1Test() {
                super("com.example.test", MyActivity.class);
            }
    
            @Override
            public void setUp() throws Exception {
                super.setUp();
                MyActivity activity = this.getActivity();
                m_assetManager = activity.getAssets();
            }
    
            @Override
            public void testSomething() throws Exception {
                InputStream stream = m_assetManager.open("myimage.png");
            }
        }
    

    You'll need to run this on the emulator as an Android Unit Test, since it depends on the main activity to load the assets.