简体   繁体   English

Robolectric:如何测试内部使用应用程序实例的类?

[英]Robolectric: how to test class which use application instance inside?

I want to test a fragment UserConnectFragment which contains a variable PlateformConnect .我想测试一个包含变量PlateformConnect的片段UserConnectFragment This class has a method to initialise Facebook SDK:这个类有一个初始化 Facebook SDK 的方法:

@Override
public void create() {
    FacebookSdk.sdkInitialize(MyApplication.getInstance().getApplicationContext());
}

I extended Android application with MyApplication class.我用MyApplication类扩展了 Android 应用程序。

In UserConnectFragment , I use PlateformConnect like that:UserConnectFragment 中,我像这样使用 PlateformConnect:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // Must be done before the content view assignement!
    PlateformConnect.getInstance().create(); 

...

In my Robolectric class test:在我的 Robolectric 课堂测试中:

@Before
public void setUp() throws Exception {
    // Create basic activity, and add fragment
    mActivity = Robolectric.buildActivity(FragmentActivity.class).create().start().resume().get();
    mUserConnectFragment = new UserConnectFragment();
    addMapFragment(mActivity, mUserConnectFragment);

    //mLoginButton = (Button)   mActivity.findViewById(R.id.facebook_button);
} 

There is a crash when this test runs:此测试运行时发生崩溃:

java.lang.NullPointerException
    at com.xxx.yyyy.ui.intro.UserConnectFragment.onViewCreated(UserConnectFragment.java:77)

And this error appears because I use:出现此错误是因为我使用:

MyApplication.getInstance().getApplicationContext()

... and getInstance() returns null. ... 并且 getInstance() 返回 null。

In my application I use MyApplication.getInstance() in a lot of class, so how can I do to test with Robolectric ??在我的应用程序中,我在很多类中使用MyApplication.getInstance() ,那么我该如何使用 Robolectric 进行测试?

Thanks guys!谢谢你们!

I found the solution: just add @Config(xxx) to set the Application class name.我找到了解决方案:只需添加@Config(xxx) 来设置应用程序类名。

@RunWith(RobolectricTestRunner.class)
@Config(application = MyApplication.class)
public class UserConnectFragmentTest {

...

More details here: http://robolectric.org/custom-test-runner/更多细节在这里: http : //robolectric.org/custom-test-runner/

ApplicationProvider.getApplicationContext()为我工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM