I'm trying to write a test case to verify a class that writes to Shared Preferences. I'm using Android Studio v1.5.
In the good old eclipse, when using AndroidTestCase, a second apk file was deployed to the device, and tests could be run using the instrumentation context, so you could run tests using the instrumentation apk's shared preferences without altering the main apk's existing shared preferences files.
I've spent all the morning trying to figure out how to get a non null context in Android Studio tests. Apparently unit tests made for eclipse are not compatible with the Android Studio testing framework, as calling getContext() returns null. I thought I've found the answer in this question: Get context of test project in Android junit test case
Things have changed over time as old versions of Android Studio didn't have full testing support. So a lot of answers are just hacks. Apparently now instead of extending InstrumentationTestCase or AndroidTestCase you should write your tests like this:
@RunWith(AndroidJUnit4.class)
@SmallTest
public class MyTest {
@Test
public void testFoo(){
Context instrumentationContext = InstrumentationRegistry.getContext();
Context mainProjectContext = InstrumentationRegistry.getTargetContext();
}
}
So now I have a non null instrumentation context, but it doesn't write any file.
If I do:
context = InstrumentationRegistry.getContext();
Then the SharedPreferences editor seems to work and no exception is thrown. On closer inspection I can see that the editor is trying to write to this file:
data/data/<package>.test/shared_prefs/PREFS_FILE_NAME.xml
Which doesn't exist!
However using this:
context = InstrumentationRegistry.getTargetContext();
the editor works correctly and the preferences are written to this file:
/data/data/<package>/shared_prefs/PREFS_FILE_NAME.xml
As far as I know, no test apk has been uploaded to the device after running the test. This might explain why the file was not written using the instrumentation context. Is it possible that this context is a fake context that fails silently?
And if this were the case, how could I obtain a REAL instrumentation context so that I can write preferences without altering the main project's preferences?
Aucun commentaire:
Enregistrer un commentaire