使用robolectric我的expectedIntent在它不应该是null时为null

时间:2016-06-06 14:28:46

标签: java android unit-testing robolectric

我有这个活动:

public class WelcomeActivity extends ActivityBase {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.welcome);

        final OnClickListener Click = new OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent = new Intent(WelcomeActivity.this, WelcomeDoneActivity.class);
                startActivityForResult(intent, 0);  

                setResult(RESULT_OK);
                finish();
            }
        };
        ((TitleBar)findViewById(R.id.theTitleBar)).setOnClickCloseListener(Click);

    }

这个测试:

@Test
public void clickingLogin_shouldStartLoginActivity() {
    WelcomeActivity activity = Robolectric.setupActivity(WelcomeActivity.class);
    activity.findViewById(R.id.theTitleBar).performClick();

    Intent expectedIntent = new Intent(activity, WelcomeDoneActivity.class);
    assertThat(shadowOf(activity).getNextStartedActivity(), equalTo(expectedIntent));
}

为什么我会收到断言错误?

java.lang.AssertionError: 
Expected: <Intent { cmp=com.w/.profile.WelcomeDoneActivity }>
     but: was null

更新

我也试过这个,但startedIntent == null

        ShadowActivity shadowActivity = shadowOf(activity);
        Intent startedIntent = shadowActivity.getNextStartedActivity();
//        ShadowIntent shadowIntent = shadowOf(startedIntent);
//        String name = startedIntent.getIntentClass().getName();
//        assertThat(shadowIntent.getIntentClass().getName(), equalTo(targetActivityName));

2 个答案:

答案 0 :(得分:0)

变化:

shadowOf(activity).getNextStartedActivity()

要:

shadowOf(activity).getNextStartedActivityForResult()

答案 1 :(得分:0)

在您发布的代码中,您将通过setOnClickCloseListener在TitleBar上设置onClick。 您的TitleBar似乎是自定义视图,setOnClickCloseListener对我来说意味着有一个&#39;关闭&#39;应该调用要执行ClickClick()的TitleBar上的按钮或视图,而不是TitleBar本身,以便Robolectric按照您期望的方式运行。

在不知道TitleBarsetOnClickCloseListener实施的情况下很难分辨,但是:

1)如果您只想点击TitleBar来启动新活动, 然后将setOnClickCloseListener更改为setOnClickListener

2)如果TitleBar包含关闭按钮/视图的视图(或任何&#34; ClickClose&#34;在setOnClickCloseListener中引用!),请深入研究TitleBar布局以查找此视图的ID,并调用performClick,它应解决您的问题。