Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get hold of an Android Context for a Junit test from a Java Project?

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!)

like image 275
jax Avatar asked Jul 03 '10 07:07

jax


People also ask

Which java framework is used to write unit tests in Android?

Junit: It is a “Unit Testing” framework for Java Applications. It is an automation framework for Unit as well as UI Testing.


2 Answers

What about using AndroidTestCase instead of a JUnit test? AndroidTestCase will provide a Context with getContext() that can be used where it's needed.

like image 76
Fred Medlin Avatar answered Nov 11 '22 10:11

Fred Medlin


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));
    }
}
like image 27
Kuba Spatny Avatar answered Nov 11 '22 10:11

Kuba Spatny