Cannot find context in class which extends TestCase

364 views Asked by At

I am writing test cases for android app classes. But I am unable to find a way to get context of this class. Below is my test case class.

public class SplashScreenActivityTest extends TestCase {
    SplashScreenActivity splashScreenActivity;
    Context context;

    public void setUp() throws Exception {
        super.setUp();
        splashScreenActivity = new SplashScreenActivity();
    }

    public void testDeviceDetailsPost() throws Exception {
     //I need to access a method here which requires context
    }
}

I looked through many questions but I cannot understand their answers.

For example this question Get context of test project in Android junit test case

3

There are 3 answers

2
barreira On

You can pass the instance variable context to the method that requires it as follows methodThatRequiresContext(context);

I'm not entirely sure what your difficulty is.

1
Vova On

You can use AndroidTestCase, this class has method getContext();

Or create class without parent and add @RunWith(AndroidJUnit4.class) to class header. And use this : InstrumentationRegistry.getTargetContext();

Reminder: i must put this test class to the androidTest package, because this classes there are integration tests.

0
MyDogTom On

Good starting points to understand testing for Android.

  1. Training Building effective unit tests (official documentation from Google)
  2. Repository Android Testing Blueprint contains examples for different kind of tests.