junit4: New Method Proposal: ExpectedException#expect(Throwable, Callable)

Many times I needed to assert a block of code in test-method to throw an exception, and check how the throwing block has changed values. I had to use try-catch.

So I would like to implement new method with such of signature ExpectedException#expect(Throwable, Callable).

Usage:

Object obj = expect( Exception.class , new Callable() { ..do and return something.. });

Usage of Lambda in Java 8:

expect( Exception.class , () -> { ..do and return something.. } )

About this issue

  • Original URL
  • State: closed
  • Created 11 years ago
  • Comments: 20 (18 by maintainers)

Most upvoted comments

I was just wishing for the same! How about:

assertThrows(Exception.class, () -> foo());
assertThrows(Exception.class, () -> foo(), e -> assertEquals("yikes!", e.getMessage()));

Note that unlike @Tibor17, I’m suggesting a third argument that allows for adding additional checks on the Exception. I.e. we would have the following signatures:

@FunctionalInteface
interface ThrowableRunnable {
    void run() throws Throwable;
}

static void assertThrows(
    Class<? extends Throwable> throwable, 
    ThrowableRunnable runnable
) {}

static <T extends Throwable> void assertThrows(
    Class<Throwable> throwable, 
    ThrowableRunnable runnable, 
    Consumer<T> exceptionConsumer
) {}

Note also that neither Callable nor Runnable are really suited for this use-case. Neither of them allows for throwing Throwable