Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit continue to assert things after expected exception

I have something like

@Test(expected = IllegalArgumentException.class)
public void cdIntoNonExistantFolder() {
    cdTool.changeDirectory("nonexistant");
    assertThat(cdTool.getStatusCode(), not(equalTo(0)));
}

I believe the assertThat does not run as changeDirectory will throw the exception. Is it possible to make it still run?

like image 484
Jiew Meng Avatar asked Feb 02 '14 01:02

Jiew Meng


2 Answers

You could use a finally:

@Test(expected = IllegalArgumentException.class)
public void cdIntoNonExistantFolder() {
    try {
        cdTool.changeDirectory("nonexistant");
    }
    finally {
        assertThat(cdTool.getStatusCode(), not(equalTo(0)));
    }
}
like image 189
MattR Avatar answered Oct 19 '22 10:10

MattR


I'd rather avoid any try/catch structures in unit-tests. Here's one possibility with Catch-Exception:

@Test
public void cdIntoNonExistantFolder() {
    catchException(cdTool).changeDirectory("nonexistant");

    assertThat(caughtException(), instanceOf(IllegalArgumentException.class));
    assertThat(cdTool.getStatusCode(), not(equalTo(0)));
}

or with JUnit 5:

@Test
public void cdIntoNonExistantFolder() {
    expectThrows(IllegalArgumentException.class, () -> {
        cdTool.changeDirectory("nonexistant");
    });

    assertThat(cdTool.getStatusCode(), not(equalTo(0)));
}
like image 20
fgb Avatar answered Oct 19 '22 11:10

fgb