0

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

Community
  • 1
  • 1

3 Answers3

0

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.

barreira
  • 9
  • 3
  • The context must contain a context just creating the variable and passing it to the method won't work. –  Dec 28 '16 at 13:11
  • like Context context = getContext(); –  Dec 28 '16 at 13:13
0

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.

Vova
  • 956
  • 8
  • 22
0

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.
MyDogTom
  • 4,486
  • 1
  • 28
  • 41