简体   繁体   中英

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

I want to test a fragment UserConnectFragment which contains a variable PlateformConnect . This class has a method to initialise Facebook SDK:

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

I extended Android application with MyApplication class.

In UserConnectFragment , I use PlateformConnect like that:

@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:

@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.

In my application I use MyApplication.getInstance() in a lot of class, so how can I do to test with Robolectric ??

Thanks guys!

I found the solution: just add @Config(xxx) to set the Application class name.

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

...

More details here: http://robolectric.org/custom-test-runner/

ApplicationProvider.getApplicationContext()为我工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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