Android Unit Tests Requiring Context

I am writing my first Android database backend and I'm struggling to unit test the creation of my database.

Currently the problem I am encountering is obtaining a valid Context object to pass to my implementation of SQLiteOpenHelper. Is there a way to get a Context object in a class extending TestCase? The solution I have thought of is to instantiate an Activity in the setup method of my TestCase and then assigning the Context of that Activity to a field variable which my test methods can access...but it seems like there should be an easier way.

Asked by: Walter727 | Posted: 25-01-2022

Answer 1

You can use InstrumentationRegistry methods to get a Context:

InstrumentationRegistry.getTargetContext() - provides the application Context of the target application.

InstrumentationRegistry.getContext() - provides the Context of this InstrumentationĂ¢â‚¬â„¢s package.

For AndroidX use InstrumentationRegistry.getInstrumentation().getTargetContext() or InstrumentationRegistry.getInstrumentation().getContext().

New API for AndroidX: ApplicationProvider.getApplicationContext()

Answered by: Darcy569 | Posted: 26-02-2022

Answer 2

You might try switching to AndroidTestCase. From looking at the docs, it seems like it should be able to provide you with a valid Context to pass to SQLiteOpenHelper.

Edit: Keep in mind that you probably have to have your tests setup in an "Android Test Project" in Eclipse, since the tests will try to execute on the emulator (or real device).

Answered by: Melissa135 | Posted: 26-02-2022

Answer 3

Your test is not a Unit test!!!

When you need

  • Context
  • Read or Write on storage
  • Access Network
  • Or change any config to test your function

You are not writing a unit test.

You need to write your test in androidTest package

Answered by: Julia897 | Posted: 26-02-2022

Answer 4

Using the AndroidTestCase:getContext() method only gives a stub Context in my experience. For my tests, I'm using an empty activity in my main app and getting the Context via that. Am also extending the test suite class with the ActivityInstrumentationTestCase2 class. Seems to work for me.

public class DatabaseTest extends ActivityInstrumentationTestCase2<EmptyActivity>
    EmptyActivity activity;
    Context mContext = null;
    public void setUp() {
        activity = getActivity();
        mContext = activity;
    ... //tests to follow

What does everyone else do?

Answered by: Kate688 | Posted: 26-02-2022

Answer 5

You can derive from MockContext and return for example a MockResources on getResources(), a valid ContentResolver on getContentResolver(), etc. That allows, with some pain, some unit tests.

The alternative is to run for example Robolectric which simulates a whole Android OS. Those would be for system tests: It's a lot slower to run.

Answered by: Emma889 | Posted: 26-02-2022

Answer 6

You should use ApplicationTestCase or ServiceTestCase.

Answered by: Haris339 | Posted: 26-02-2022

Answer 7

Extending AndroidTestCase and calling AndroidTestCase:getContext() has worked fine for me to get Context for and use it with an SQLiteDatabase.

The only niggle is that the database it creates and/or uses will be the same as the one used by the production application so you will probably want to use a different filename for both


  public static final String    NOTES_DB      = "notestore.db";
  public  static final String   DEBUG_NOTES_DB = "DEBUG_notestore.db";

Answered by: Rafael292 | Posted: 26-02-2022

Answer 8

First Create Test Class under (androidTest).

Now use following code:

public class YourDBTest extends InstrumentationTestCase {

private DBContracts.DatabaseHelper db;
private RenamingDelegatingContext context;

public void setUp() throws Exception {
    context = new RenamingDelegatingContext(getInstrumentation().getTargetContext(), "test_");
    db = new DBContracts.DatabaseHelper(context);

public void tearDown() throws Exception {

public void test1() throws Exception {
    // here is your context
    context = context;

Answered by: Maya206 | Posted: 26-02-2022

Answer 9

Initialize context like this in your Test File

private val context = mock(

Answered by: Leonardo606 | Posted: 26-02-2022

Similar questions

android - Toast message requiring user to fill in blank "EditText" fields

I am trying to get a message to appear when a button is clicked to tell the user to fill in the blank field. Currently, if the field is blank, it crashes/force closes the app. I tried to do the following code and had zero success. Originally I didn't have the if/else in there, I just ran the calculator(); method and the following imm code. Could someone point me into the right direction? public...

java - How to make Android app requiring camera support to run on Samsung Galaxy Mini and similar devices?

I have found out that Android app that has requirement android.permission.CAMERA will not even show up in Android Market for device like Samsung Galaxy Mini. I think it is because Samsung Galaxy Mini has only fixed-focus camera. Has anyone created app with camera requirements and has successfully deployed it on Android Market where it is possible to install it on Samsung Galaxy Mini ? ...

Requiring OpenGL ES 2 in Android App

Just to be sure, when requiring ES2 in Android app, you just need to append android:glEsVersion="0x00020000" to any uses-feature tag? Should this actually be its own uses-feature tag? Are there any issues with this being combined as an attribute in another uses-feature tags that requires a particular hardware?

java - Kindle fire HD shows my app in portrait when i am requiring landscape

I have an app that runs in landscape mode. It's supposed to always be in landscape mode, but if I start it on my Kindle Fire HD holding it vertically, the app will briefly try to display in portrait mode. This causes much grief. This brief portrait behavior doesn't happen on my phone or on the Kindle fire HD emulator. Is there a way to prevent this from happening? My manifest file has: ...

android - requiring editView boxes be completed before moving to another activity

Here is my current section I'm looking at: public void ButtonOnClick(View v) { Intent intent = new Intent(this, MainActivity.class); EditText debtors = (EditText) findViewById(; String debtor = debtors.getText().toString(); EditText myEdit = (EditText) findViewById(; String myEditValue = myEdit.getText().toString(); ...

bitmap - Samsung devices requiring large heap size in Android

I've created an Android game which uses a few full screen bitmaps (4 @ 800x480) and maybe 10 Sprites (about 80x80), so it's not particularly large. The game runs absolutely fine on an old HTC Desire with 100mb free ram and 25mb free storage. It also runs fine on several high end HTC phones, a Motorola XOOM tablet, Nexus 5, Nexus 7 and a couple of Archos/Arnova tablets. However when I run it on a Samsung device (currently S...

android - Any easy way to redirect a video file into a program requiring camera?

To make inputting text into a CLI program easier, we can use file redirection. For example, we can use mypro.exe &lt;input.txt instead of running mypro.exe and entering texts from a keyboard later, which is tedious when frequently running the program with the same input, like in manual testing. We are developing an Android application detecting human face, eyes, shaking, blinks, et...

android - Does Xamarin C# apps work without requiring Mono compiler?

I mean, if I send an apk developed in Xamarin to my friend to install, does he needs Mono framework on his phone or it will install and run without any 3rd party application?

c++ - Android - NDK - Variadic macro requiring 1+ args

I have the following macro in a logging library of mine : #define TRACE_E(__logCat,__format,...) \ do { \ ::dbg::LogCategory * const __catPtrVal = (::dbg::LogCategory *)(__logCat); \ if( NULL != __catPtrVal &amp;&amp; __catPtrVal-&gt;IsEnabled() ) \ { \ __catPtrVal-&gt;Error( __format, __VA_ARGS__ ); \ } \ } while( false ) Under Visual St...

locking - Android Lock Screen: allow user to answer phone call without requiring PIN

I am building a custom Android lock screen with custom PIN. I would like to allow users to answer incoming calls without having to enter the PIN and without compromising the security of the phone. Both Next Lock Screen and GoLocker have this feature. Two bad alternatives: (1) force the user to enter the PIN or (2) completely unlock the phone when the user receives a phone call Any suggestions, pleas...

Still can't find your answer? Check out these communities...

Android Google Support | Android Community | Android Community (Facebook) | Android