44

I have a class that creates (or opens) a file to write some data to it. This class receives a Context in the constructor, saves it in an instance field, and then uses it to call the context.openFileOutput method.

When running the application, I instantiate this class by passing the ApplicationContext as the Context, and everything is working as expected.

However, when I try to test this class with an Instrumentation Test, I get a NullPointerException. I'm passing the getInstrumentation().getContext() context, which I know corresponds to the context of the test, and not the one of the real app.

getInstrumentation().getContext().openFileOutput("myFile", Context.MODE_PRIVATE); // This throws NullPointerException :( :(

Within the test, I need this file to be created in the test package and not in the app package, as I don't want overwrite the file in my app.

I know there is a RenamingDelegatingContext class out there, but I cannot pass this context to my class since my class also opens a raw resource, and I want that resource to be different when running the test (something like a mocked resource).

I searched a lot about this, and there is no documentation about the Instrumentation Context. I couldn't find its limitations nor anything that solves my problem.

Do you know how to tackle this?

1
  • 2
    did you ever find a solution?
    – Brian Risk
    Apr 28, 2017 at 20:03

1 Answer 1

-2

I can't recall when this was changed, but the current method to get a Context object during Instrumented testing is to import

import android.support.test.InstrumentationRegistry;

and call

InstrumentationRegistry.getContext();

Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.