I'm writing a small app and have encountered the following issue:
@Test
public void givenSkiExists_whenAddingNewSki_thenThrowEntityAlreadyPresentException () {
skiManager.addEntity(new Ski(new SkiType("name1", "description1"), "brand1", "model1", "bond1", 1f));
assertThrows(EntityAlreadyPresentException.class, () -> skiManager.addEntity(new Ski(new SkiType("name1", "description1"), "brand1", "model1", "bond1", 1f)));
}
the first skiManager.addEntity can throw multiple custom errors, but this test is not designed to check that, it assumes the first addEntity will work correctly, but I still need to handle the unhandled exceptions, and my question is:
Do I let it crash by just adding throws Exception
to the unit test declaration or should I wrap it with try {...} catch (Exception e) {fail(e.message);}
? is there any advantage to the second approach?
A test suite passes when all the tests in it pass or are skipped. If any test fails or errors out, the test suite does not pass.
With that in mind, there are very few practical differences between failing a test and allowing it to error out. Unless your catch
block adds some useful behavior/info, I'd just let the test error out, and not bother with the boilerplate of catching all those exceptions in every test just to fail it.
For example:
catch (MyConfigException e) {
fail("Got a MyConfigException. " +
"This probably means you forgot to set teh SOME_CONFIG env vairable",
e);
}
If multiple tests rely on the same set up logic, it might be a good idea to move it to some setup method, so if it errors out you get a clear indication where the problem was instead of having multiple tests failing for the same underlying reason.
For example:
public class SkiTests
private SkiManager skiManager;
@Before
public void setUp() {
// Set up the SkiManager...
// Set up the first entity
skiManager.addEntity(new Ski(new SkiType("name1", "description1"), "brand1", "model1", "bond1", 1f));
}
@Test
public void givenSkiExists_whenAddingNewSki_thenThrowEntityAlreadyPresentException () {
assertThrows(EntityAlreadyPresentException.class, () -> skiManager.addEntity(new Ski(new SkiType("name1", "description1"), "brand1", "model1", "bond1", 1f)));
}
@Test
public void testSomethingElseWithTheSameEntity() {
//...
}