android - Robolectric:如何测试内部使用应用程序实例的类?

标签 android robolectric

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

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

我用 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(); 

...

在我的 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);
} 

此测试运行时发生崩溃:

java.lang.NullPointerException
    at com.xxx.yyyy.ui.intro.UserConnectFragment.onViewCreated(UserConnectFragment.java:77)

出现这个错误是因为我使用了:

MyApplication.getInstance().getApplicationContext()

... getInstance() 返回 null。

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

谢谢大家!

最佳答案

我找到了解决方案:只需添加@Config(xxx) 来设置应用程序类名。

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

...

此处有更多详细信息:http://robolectric.org/custom-test-runner/

关于android - Robolectric:如何测试内部使用应用程序实例的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30735936/

相关文章:

android - Kotlin 创建一个 snackbar

android - 尝试添加下拉刷新时 Webview 崩溃

android - ImageAnalysis.Analyzer 只触发一次

java - 使用 JUnit 在参数化测试类中使用枚举成员时出现异常

java - 如何仅在测试运行时忽略类或方法

java - 在 Robolectric 3.1.2 中设置 FakeHttp.setDefaultHttpResponse 没有给我响应

android - 使用 Robolectric 和 ORMLite 进行测试时使用模拟数据库

android - Robolectric 3.0 测试 - Android

java - 无法在分离 View 上启动此动画师!显露效果

android - 为 Android 模拟器创建我自己的磁盘