android - How to get the activity reference before its oncreate gets called during testing -
how reference of activity before oncreate called. while under test. use activitytestrule junit rule. reason requirement want inject mocks activity tests.
public class myactivity extends activity{ mycomponent mycomponent; @override public void oncreate(bundle savedinstancestate){ super.oncreate(savedinstancestate); if(mycomponent==null){ mycomponent ... //initialise dagger component } mycomponent.inject(this); ... } public void setcomponent(mycomponent comp){ this.mycomponent = comp; } } public class mytest{ @rule public activitytestrule<myactivity> intentstestrule = new activitytestrule<>(myactivity.class); mycomponent myfakecomponent; @before public void setup() { myactivity activity = intentstestrule.getactivity(); activity.setcomponent(myfakecomponent); } @test public void testmethod1(){...} }
as per documentation, you're doing here wrong.
@rule public activitytestrule<myactivity> intentstestrule = new activitytestrule<>(myactivity.class); mycomponent myfakecomponent; @before public void setup() { myactivity activity = intentstestrule.getactivity(); activity.setcomponent(myfakecomponent); }
because,
this rule provides functional testing of single activity. activity under test launched before each test annotated test , before methods annotated @before. terminated after test completed , methods annotated after finished. during duration of test able manipulate activity directly.
however!
protected void beforeactivitylaunched ()
override method execute code should run before activity created , launched. method called before each test method, including method annotated @before.
therefore, if move initialization of mainactivitycomponent
outside activity place mockable, you'll able tinker before main activity created.
edit:
another possible solution lazily initiate activity per link.
@rule public activitytestrule<notedetailactivity> mnotedetailactivitytestrule = new activitytestrule<>(notedetailactivity.class, true /* initial touch mode */, false /* lazily launch activity */); @before public void intentwithstubbednoteid() { // add note stub fake service api layer. fakenotesserviceapiimpl.addnotes(note); // lazily start activity activitytestrule time inject start intent intent startintent = new intent(); startintent.putextra(notedetailactivity.extra_note_id, note.getid()); mnotedetailactivitytestrule.launchactivity(startintent); registeridlingresource(); }
Comments
Post a Comment