Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 446
anthony Avatar asked Jun 09 '15 15:06

anthony


People also ask

What are the disadvantages of using Robolectric?

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.

Is Robolectric deprecated?

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.


2 Answers

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/

like image 174
anthony Avatar answered Oct 25 '22 19:10

anthony


ApplicationProvider.getApplicationContext() worked for me.

like image 25
Bitcoin Cash - ADA enthusiast Avatar answered Oct 25 '22 19:10

Bitcoin Cash - ADA enthusiast