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
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);
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.
I am using Robolectric 3.2. This is what I used:
ShadowApplication.getInstance().getApplicationContext();
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