Maxim Popravko
Maxim Popravko

Reputation: 4169

How can I get context of test application itself in ApplicationTestCase<MyApp>?

How can I get context of test application itself in ApplicationTestCase<MyApp>?

I use test application's resources to store some reference data, but I cannot acquire it's context, as far as I see.

I'm trying to do the following:

referenceContents = readRawTextFile(
    getSystemContext(),
    //test application's res namespace is myApp.test.* 
    myApp.test.R.raw.reference_file);

where readRawTextFile is simple text reader routine, but the data I get is wrong.

Upvotes: 2

Views: 2037

Answers (1)

AgentKnopf
AgentKnopf

Reputation: 4345

If you need the context of the application you're testing (i.e. MyApp) then this is how you do it:

public class MyAppTest extends ApplicationTestCase<MyApp> {

    public MyAppTest () {
        super(MyApp.class);
    }

    public MyAppTest (Class<MyApp> applicationClass) {
        super(applicationClass);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        createApplication();
    }

    public void testMyApp() throws Exception {
        // Retrieves a file in the res/xml folder named test.xml
        XmlPullParser xml = getContext().getResources().getXml(R.xml.test);
        assertNull(xml);
    }
}

As you can see, you get the context of your application under test using:

getContext()

in your test case.

However if you have two separate projects: One is your application and one is your test project and you need the context of the testproject, then the only choice you have is to extend InstrumentationTestCase instead of ApplicationTestCase - however, this means that you won't be able to obtain a context of the application project, but only a context of your test project.

Upvotes: 4

Related Questions