Android JUnit Testing … How to Expect an Exception

后端 未结 3 1503
难免孤独
难免孤独 2021-02-04 23:21

I\'m attempting to write some tests using the built-in android Junit testing framework. I am running into a problem with a test where I am expecting an exception to be thrown.

3条回答
  •  执笔经年
    2021-02-05 00:12

    Now JUnit4 is available via Android SDK (refer to android-test-kit)

    Update: it's official now on d.android.com:

    The AndroidJUnitRunner is a new unbundled test runner for Android, which is part of the Android Support Test Library and can be downloaded via the Android Support Repository. The new runner contains all improvements of GoogleInstrumentationTestRunner and adds more features:

    • JUnit4 support
    • Instrumentation Registry for accessing Instrumentation, Context and Bundle Arguments
    • Test Filters @SdkSupress and @RequiresDevice
    • Test timeouts
    • Sharding of tests
    • RunListener support to hook into the test run lifecycle
    • Activity monitoring mechanism ActivityLifecycleMonitorRegistry

    So, JUnit4 style of exception testing using expected annotation:

    @Test(expected= IndexOutOfBoundsException.class) 
    public void empty() { 
         new ArrayList().get(0); 
    }
    
    
    

    or expected exception rules:

    @Rule
    public ExpectedException thrown = ExpectedException.none();
    
    @Test
    public void shouldTestExceptionMessage() throws IndexOutOfBoundsException {
        List list = new ArrayList();
    
        thrown.expect(IndexOutOfBoundsException.class);
        thrown.expectMessage("Index: 0, Size: 0");
        list.get(0); // execution will never get past this line
    }
    
    
    

    is also possible.

    Refer to official documentation for more details on how to setup test support library.

    提交回复
    热议问题