I need to access and Android context for a JUnit Test.
I have tried using MockContext and extending the AndroidTestCase but each time I get an error saying (stub!)
Junit: It is a “Unit Testing” framework for Java Applications. It is an automation framework for Unit as well as UI Testing.
What about using AndroidTestCase instead of a JUnit test? AndroidTestCase will provide a Context with getContext() that can be used where it's needed.
Another way to access context from JUnit without extending AndroidTestCase
is to use Rule
to launch an activity under test. Rules are interceptors which are executed for each test method and will run before any of your setup code in the @Before
method. Rules were presented as a replacement for the ActivityInstrumentationTestCase2
.
@RunWith(AndroidJUnit4.class)
@SmallTest
public class ConnectivityTest {
@Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void testIsConnected() throws Exception {
Context context = mActivityRule.getActivity().getBaseContext();
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean connected = cm.getActiveNetworkInfo().isConnectedOrConnecting();
Assert.assertEquals(connected, ConnectionUtils.isConnected(context));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With