1

I'm trying to setup unit tests inside Android Studio (which supposedly is still 'experimental'). How do I get a Context? All the examples I see call AndroidTestCase.getContext() but in my tests this returns null.

public class DummyTest extends AndroidTestCase {

    public void testExample() throws Exception {
         Context c = getContext();
         assertNotNull(c);
    }

}

This will result in a AssertionFailedError because the returned context is null.

AndySavage
  • 1,729
  • 1
  • 20
  • 34
  • This has been asked before. Please see my answer: http://stackoverflow.com/a/29063736/950427. – Jared Burrows Mar 25 '15 at 17:47
  • Here is an open source project utilizing android's new testing: https://github.com/JakeWharton/NotRxAndroid/blob/master/rxandroid/src/androidTest/java/rx/android/view/RxViewTest.java. – Jared Burrows Mar 25 '15 at 17:55
  • @JaredBurrows Ah. I hadn't seen your answer when I searched - though I'm not progressing. Your answer suggests creating a `MockContext`, which I then can't call `getSharedPreferences` from (as it returns null). Am I going to have to mock this too? – AndySavage Mar 25 '15 at 18:40
  • I am not sure. I have used Robolectric in the past for all my tests. They have a "mock" context that works very well. Google documents/poorely documents their new testing support. – Jared Burrows Mar 25 '15 at 19:38

0 Answers0