Robolectric:如何测试里面使用应用程序实例的类?

ant*_*ony 6 android robolectric

我想测试一个包含变量PlateformConnect的片段UserConnectFragment.这个类有一个初始化Facebook SDK的方法:

@Override
public void create() {
    FacebookSdk.sdkInitialize(MyApplication.getInstance().getApplicationContext());
}
Run Code Online (Sandbox Code Playgroud)

我用MyApplication类扩展了Android应用程序.

UserConnectFragment中,我使用PlateformConnect:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // Must be done before the content view assignement!
    PlateformConnect.getInstance().create(); 

...
Run Code Online (Sandbox Code Playgroud)

在我的Robolectric类测试中:

@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);
} 
Run Code Online (Sandbox Code Playgroud)

此测试运行时发生崩溃:

java.lang.NullPointerException
    at com.xxx.yyyy.ui.intro.UserConnectFragment.onViewCreated(UserConnectFragment.java:77)
Run Code Online (Sandbox Code Playgroud)

出现此错误是因为我使用:

MyApplication.getInstance().getApplicationContext()
Run Code Online (Sandbox Code Playgroud)

...和getInstance()返回null.

在我的应用程序中,我在很多类中使用MyApplication.getInstance(),那么我该如何使用Robolectric进行测试?

多谢你们!

ant*_*ony 7

我找到了解决方案:只需添加@Config(xxx)来设置Application类名.

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

...
Run Code Online (Sandbox Code Playgroud)

更多细节:http://robolectric.org/custom-test-runner/