Android JUnit Testing … How to Expect an Exception

后端 未结 3 1500
难免孤独
难免孤独 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:20

    I've been looking for some good solutions, however, none of the solutions was really satisfying to me. So, I created my own.

    public final void assertThrows(VoidFunction v, Class e) {
        try {
            v.call();
        } catch (Exception ex) {
            if (!ex.getClass().equals(e)) {
                Assert.fail();
            }
            // Do nothing, basically succeeds test if same exception was thrown.
            return;
        }
    
        // Fails if no exception is thrown by default.
        Assert.fail();
    }
    

    Where VoidFunction is a simple interface:

    @FunctionalInterface
    public interface VoidFunction {
        void call();
    }
    

    This is used as follows (for example):

    @Test
    public void testFoo() {
        assertThrows(() -> foo.bar(null)), NullPointerException.class);
        assertThrows(() -> foo.setPositiveInt(-5)), IllegalArgumentException.class);
        assertThrows(() -> foo.getObjectAt(-100)), IndexOutOfBoundsException.class);
        assertThrows(new VoidFunction() {
                @Override
                public void call() {
                    foo.getObjectAt(-100);
                }
            }, IndexOutOfBoundsException.class); // Success
        assertThrows(new VoidFunction() {
                    @Override
                    public void call() {
                        throw new Exception();
                    }
                }, NullPointerException.class); // Fail
    
    }
    

    I included one call without using the lambda, this makes it easier to understand code sometimes, at least for me. Simple to use and it allows multiple exception catches in ONE method.

提交回复
热议问题