Search code examples
androidandroid-testingbitmapfactory

having trouble converting from resource to bitmap in an android test


Iam attempting to convert a resource image to a bitmap to test it in an Instrumentation test in android. originally i had this as a regular test extending testcase. my issue is with this

 protected void setUp()
{
 testbmap=BitmapFactory.decodeResource(getInstrumentation().
 getContext().getResources(), R.drawable.ic_launcher);
}

then i test that the bitmap is not null but the test fails.

public void testnotnull()
{
 assertNotNull(testbmap);
}

so iam doing something wrong here i think it could b something to do with the first param in the decoderecource(), maybe iam not pointing to the correct resources? I also tried getApplicationContext.getResources() method but iam not too sure on this one. can anyone help me?


Solution

  • I solved this problem changing #getContext() which will return Context of instrumentation's package to #getTargetContext() which will return context of target application.

    Return a Context for the target application being instrumented. Note that this is often different than the Context of the instrumentation code, since the instrumentation code often lives is a different package than that of the application it is running against. See getContext to retrieve a Context for the instrumentation code.

    Kotlin method:

    @Test
    fun bitmapIsNotNull() {
        val context = InstrumentationRegistry.getInstrumentation().targetContext
        val bitmap = BitmapFactory.decodeResource(context.resources, R.raw.any_image)
    
        Assert.assertNotNull(bitmap)
    }