Deathtiny Deathtiny - 10 months ago 120
Java Question

How to continue test after JUnit ExpectedException if thrown?

I have set up some JUnit (4.12) test with the ExpectedException feature, and I would like the test to continue after the expected exception. But I never see the log '3', as the execution seems to stop after the exception, event if catch?

Is this actually possible, and how?

public ExpectedException exception = ExpectedException.none();

public void testUserAlreadyExists() throws Exception {"1");

// Create some users
Assert.assertTrue( userService.userExists("toto1") );
Assert.assertTrue( userService.userExists("toto2") );
Assert.assertTrue( userService.userExists("toto3") );"2");

// Try to create an existing user

Answer Source

You cannot do that, when the exception is thrown it's thrown for real, ExpectedException rule or not.

If you really want this kind of behaviour, you can go back to the "old school" pattern:

try {
    userService.createUser("toto1");"expecting some AlreadyExistsException here")
} catch (AlreadyExistsException e) {
    // ignore

But I wouldn't bother for some log.