Robolectric 3.0 与 Facebook SDK 4.0

Robolectric 3.0 with Facebook sdk 4.0

我正在尝试让我的测试与 Robolectric.setupActivity(LoginActivity.class); 一起工作,其中我的 class 使用 facebook sdk 4.0 进行登录。即使我添加了 FacebookSdk.sdkInitialize(this); 如下:

public class LoginActivity extends FragmentActivity {

    private FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        FacebookSdk.sdkInitialize(this);

        if (savedInstanceState == null) {
            fragmentManager = getSupportFragmentManager();
            ...
        }
    }

我在测试中遇到以下错误:

java.lang.RuntimeException at LoginActivityTest.java:32
        Caused by: com.facebook.FacebookSdkNotInitializedException at LoginActivityTest.java:32

这是我的测试class:

@RunWith(CustomRobolectricRunner.class)
@Config(emulateSdk = 21, reportSdk = 21, constants = BuildConfig.class)
public class LoginActivityTest {

    private Button loginButton;
    private ShadowActivity loginActivityShadow;

    @Before
    public void setUp() throws Exception
    {
        LoginActivity activity = Robolectric.setupActivity(LoginActivity.class);

        loginButton = (Button) activity.findViewById(R.id.loginButton);
        loginActivityShadow = Shadows.shadowOf(activity);
    }

    @Test
    public void shouldStartFacebookActivityWhenLoginButtonIsClicked()
    {
        Intent intent = loginActivityShadow.getNextStartedActivity();
        loginButton.performClick();
        //assertThat(activity, new StartedMatcher(com.facebook.LoginActivity.class));
    }

}

感谢您的帮助。

您需要在致电 setContentView(R.layout.activity_login); 之前致电 FacebookSdk.sdkInitialize(this);