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

2.1k views Asked by At

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!

2

There are 2 answers

0
anthony On

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/

1
Bitcoin Cash - ADA enthusiast On

ApplicationProvider.getApplicationContext() worked for me.