how can I mock the Context using Mockito and Robolectric?

14,633

Solution 1

For robolectric 3.0, to get the Context object you simply use:

RuntimeEnvironment.application.getApplicationContext();

In your code above, you don't have to explicitly create the activity object and call it's onCreate() method. Robolectric can setup activity for you using:

searchActivity = Robolectric.setupActivity(SearchTest.class);

Solution 2

For getting the Context of the Activity or Application you can use :

Robolectric.getShadowApplication().getApplicationContext();

For Example :

Context context = Robolectric.getShadowApplication().getApplicationContext();

Now use the context variable.

Solution 3

I am using Robolectric 3.2. This is what I used:

ShadowApplication.getInstance().getApplicationContext();

Share:
14,633
Jimmy
Author by

Jimmy

#SOreadytohelp

Updated on June 09, 2022

Comments

  • Jimmy
    Jimmy almost 2 years

    This is a snippet of my activity :

    public class Search extends Activity
    {
        private String TAG = "SEARCH";
    
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.search);
            Log.d(TAG, "About to call initialastion");
       //        new InitialisationTask(this).execute();
        }
    }
    

    With the line above commented, I can happily create and execute unit tests like so :

    @RunWith(RobolectricTestRunner.class)
    public class SearchTest {
        private Search searchActivity;
        private Button searchButton;
        private Button clearButton;
        private Button loginButton;
        private Button registerButton;
        private EditText searchEditText;
    
        @Before
        public void setUp() throws Exception {
            searchActivity = new Search();
            searchActivity.onCreate(null);
    
            searchButton = (Button) searchActivity.findViewById(R.id.btnPlateSearch);
            clearButton = (Button) searchActivity.findViewById(R.id.btnClearSearch);
            loginButton = (Button) searchActivity.findViewById(R.id.btnLogin);
            registerButton = (Button) searchActivity.findViewById(R.id.btnRegister);
            searchEditText = (EditText) searchActivity.findViewById(R.id.editTextInputPlate);
        }
    
    
        @Test
        public void assertSearchButtonHasCorrectLabel()
        {
            assertThat((String) searchButton.getText(), equalTo("Search"));
        }
    }
    

    However, if I uncomment the line new InitialisationTask(this).execute(); in my activity, my tests start to fail, most likely because of the reference to this.

    What is the best approach for mocking the context?

    I have tried to add contextMock = mock(Context.class); into my setUp() however I'm not sure how I can set this mock "into" the searchActivity

    Thanks