Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I mock the Context using Mockito and Robolectric?

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

like image 206
Jimmy Avatar asked May 23 '12 17:05

Jimmy


3 Answers

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);
like image 157
Kanishk Avatar answered Sep 23 '22 21:09

Kanishk


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.

like image 21
Virag Brahme Avatar answered Sep 22 '22 21:09

Virag Brahme


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

ShadowApplication.getInstance().getApplicationContext();

like image 32
Keith Holliday Avatar answered Sep 22 '22 21:09

Keith Holliday