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!
So the main benefit about Robolectric is that it is a lot faster than Espresso or Instrumented tests in general. The downside is that it fakes an Android environment which you should be aware of. To validate real world problems, better use a classic Android Framework approach.
Robolectric is intended to be fully compatible with Android's official testing libraries since version 4.0. As such we encourage you to try these new APIs and provide feedback. At some point the Robolectric equivalents will be deprecated and removed.
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()
worked for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With