Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing Android using ActivityUnitTestCase and PreferenceManager

I have an Activity I am unit testing. I want to test the Activity in isolation, so the ActivityUnitTestCase fits my purposes very well.

The onCreate method of my Activity uses a value that is stored in the Preferences. I would like to set a value for this in my test case.

The problem is that I can't figure out how to set the Preference ahead of time. There is not a getContext() method in ActivityUnitTestCase, and getActivity(), which should return a context, is null until I call startActivity(). This is not an option because calling startActivity will trigger the onCreate method, and this is where the preferences code lives.

Any thoughts on how I can get a context that I can use to manipulate the preferences for my unit tests?

like image 649
jacobhyphenated Avatar asked Feb 08 '13 19:02

jacobhyphenated


1 Answers

You can get the context via the instrumentation.

To get the Context of instrumentation (test runner):

getInstrumentation().getContext()

But you probably need the context of the instrumented application:

getInstrumentation().getTargetContext()
like image 69
dmaxi Avatar answered Nov 18 '22 17:11

dmaxi