Robolectric: how to test a class that uses an application instance inside?

I want to test the UserConnectFragment fragment that contains the PlateformConnect variable. This class has a Facebook SDK initialization method:

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

I have expanded the Android application with the MyApplication class.

In UserConnectFragment, I use PlateformConnect as follows:

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

 @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); } 

This test fails:

 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 many classes, so how can I do this with Robolectric ??

Thanks guys!

+5
source share
1 answer

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

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

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

+6
source

All Articles