Search code examples
androidandroid-custom-viewandroid-instrumentation

Android InstrumentationTestCase on custom view using resource, not found


I have a custom view that creates Views dynamically.

public class MyCustomView extends LinearLayout {
    ...
    private View foo() {
        View view = new View(getContext());
        view.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.gray));
        return view;
    }
}

And when I test foo(), I get a resource not found exception.

public class MyCustomViewTest extends InstrumentationTestCase {
    ...
    public void testFoo() {
        View view = myCustomView.foo();
        assertNotNull(view);
    }
}

android.content.res.Resources$NotFoundException: Resource ID #0x7f0c0022

How can I get the test to see my color Resources?


Solution

  • It's possible through getTargetContext(). I previously had

    myCustomView = new MyCustomView(getInstrumentation().getContext());
    

    and replaced it with

    myCustomView = new MyCustomView(getInstrumentation().getTargetContext());