如何在测试过程中调用oncreate之前获取活动引用 [英] How to get the activity reference before its oncreate gets called during testing

查看:0
本文介绍了如何在测试过程中调用oncreate之前获取活动引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在调用活动的onCreate之前获取活动的引用。虽然它还在测试中。我使用ActivityTestRule作为JUnit规则。此要求的原因是我想将Mock注入到来自测试的活动中。

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(){...}
} 

推荐答案

根据文档,您在此处所做的操作是错误的。

@Rule
public ActivityTestRule<MyActivity> intentsTestRule = new ActivityTestRule<>(MyActivity.class);

MyComponent myFakeComponent;

@Before                                      
public void setUp() {                        
    MyActivity activity = intentsTestRule.getActivity();  
    activity.setComponent(myFakeComponent);
}              

因为,

此规则提供单个活动的功能测试。 测试中的活动将在每个带有注释的测试之前启动 使用@Beres.注释的测试和之前方法。 它将在测试完成后终止,并且方法 带After的注释已完成。在测试期间 您将能够直接操作您的活动。

然而!

protected void beforeActivityLaunched ()
重写此方法以执行任何应运行的代码 在创建和启动您的活动之前。 此方法在每个测试方法之前调用, 包括任何带有@BEFORE注解的方法。

因此,如果将MainActivityComponent的初始化移到可模拟的位置,则可以在创建主活动之前将其拼凑在一起。

编辑:

另一种可能的解决方案是按照link懒惰地启动活动。

@Rule
public ActivityTestRule<NoteDetailActivity> mNoteDetailActivityTestRule =
        new ActivityTestRule<>(NoteDetailActivity.class, true /* Initial touch mode  */,
                false /* Lazily launch activity */);

@Before
public void intentWithStubbedNoteId() {
   // Add a note stub to the fake service api layer.
   FakeNotesServiceApiImpl.addNotes(NOTE);

   // Lazily start the Activity from the ActivityTestRule this time to inject the start Intent
   Intent startIntent = new Intent();
   startIntent.putExtra(NoteDetailActivity.EXTRA_NOTE_ID, NOTE.getId());
   mNoteDetailActivityTestRule.launchActivity(startIntent);

   registerIdlingResource();
}

这篇关于如何在测试过程中调用oncreate之前获取活动引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆