vendredi 4 septembre 2015

Robolectric + Mockito, Verify a method gets called from onCreate

Consider the following Activity:

public class DavesActivity extends Activity {

    public boolean isFalse = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.whatever); 
        davesMethod();
        isFalse = true;
     } 

    public void davesMethod(){
        // do stuff
    }
}

It has the following test:

@RunWith(RobolectricTestRunner.class)
public class DavesActivityTest {
    @Test
    public void isFalse__shouldBeFalse(){
        DavesActivity activity = Robolectric.buildActivity(DavesActivity.class)
            .create().visible().get();
        activity = spy(activity);
        assertThat(activity.isFalse).isFalse(); // fails, its true 
    }

    @Test
    public void davesMethod__shouldBeCalled(){
        DavesActivity activity = Robolectric.buildActivity(DavesActivity.class)
            .create().visible().get();
        activity = spy(activity);
        Mockito.verify(activity).davesMethod(); // fails, Wanted but not invoked
    }
}

Because isFalse is changing to true I can assume onCreate is being called when I initialize my activity with Robolectric, but I have no way of spying on its first run of onCreate. Is there a way to spy on the activity, and then have it run onCreate using Robolectric without calling activity.onCreate()?

Aucun commentaire:

Enregistrer un commentaire