robospock / RoboSpock

A testing framework which brings powers of Spock and Groovy to Android app testing
http://robospock.org
MIT License
249 stars 44 forks source link

test onCreate but setup activity's field before #27

Closed droidguyg1 closed 9 years ago

droidguyg1 commented 10 years ago

My NoteView activity in onCreate uses a helper class. I want to test that it calls the helper class correctly. How do I write a robospock test for it? My best shot is:

def "should ..."() {
    when:
    def bundle = new Bundle().putLong(NotesDbAdapter.KEY_ROWID,11)
    def dbHelper = Mock(INotesDbAdapter);
    // Need to call this before onCreate() is called:  activity.setDatabaseHelper(dbHelper)
    def activity = Robolectric.buildActivity(NoteView).create(bundle).get()

    then:
    ... I check here that the dbHelper was called correctly...
}
pjakubczyk commented 10 years ago

One of the easiest ways is to use DI (RoboGuice or Dagger). It will provide you API to provide a test object while you're creating the activity. Otherwise you'd need split object creation and object calling in onStart and onCreate so Robolectric could give a window where to assign a DB mock to your activity.