mercredi 3 février 2016

Android Studio: How to get a non null Context in instrumented tests

I'm trying to write some unit tests for a Shared Preferences class in Android Studio v1.5.

I'm extending AndroidTestCase as we used to do in eclipse. However getContext() returns null. As you might remember, in eclipse a second apk was compiled and deployed to the device, and everything needing a context could be easily tested (InstrumentationTestCase, AndroidTestCase, ApplicationTestCase, etc). It just worked and we loved it. It took a few minutes to create a test project and get a test running.

Now in Android Studio, which is allegedly better at everything, I've spent the entire morning tweaking the build.gradle file to run the tests that are created by default when you create a project, and I'm still unable to get the instrumented tests working. Because somehow somebody though having getContext() to return null is normal

Before you even suggest it, be aware I've already read this: Android Developers Training: Building Local Unit Tests

and yes I know you can mock the context with Mockito and run the tests as regular jUnit tests in the local machine.

This is not what I want. I want the real thing. I need the actual shared preferences file to be created in the device.

So this question is also useless for me.

I've also read the guide for instrumented tests: Android Developers Training: Building Instrumented Unit Tests

Where absolutely nothing is mentioned about getting the context.

TL;DR Is getting a real Context even possible in Android Studio instrumented tests?

Aucun commentaire:

Enregistrer un commentaire