How to expect an exception in Robotium?

扶醉桌前 提交于 2019-12-20 03:53:12

问题


Here is my test case:

public void testStartActivityWithoutExtraData() {
    try {
        getActivity();
        Assert.fail("Should have thrown IllegalStateException");
    } catch (IllegalStateException ex) {
        assertTrue(true);
    }
}

The Activity under a test throws an Exception if it is started without extras. So in this test I expect for an IllegalStateException, but test always fails because of the issue:

Test failed to run to completion. Reason: 'Instrumentation run failed due to 'java.lang.IllegalStateException''. Check device logcat for details
Test running failed: Instrumentation run failed due to 'java.lang.IllegalStateException'

Logcat is just saying the Application thrown an Exception which is very expected. So how to handle it in a test? Thank you.

Update Here is the code I'm actually testing:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_item_activity);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        Bundle bundle = getIntent().getExtras();

        if (savedInstanceState == null) {
            if (bundle != null) {
                EditItemFragment editItemFragment = EditItemFragment.newInstance(bundle.getInt
                        ("id")); 
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.add(R.id.edit_item_activity_frame, editItemFragment).commit();
            } else {
                throw new IllegalStateException(TAG + " should be invoked with Extras (id for " +
                        "ticket)");
            }
        }
    }

来源:https://stackoverflow.com/questions/15153668/how-to-expect-an-exception-in-robotium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!