hanki.dev

Unit test for a specific exception message | Java

I used to use AssertJ in unit tests where I had to check for a specific exception message. My colleague recently found a simple way to do this with no extra dependencies, using a try/catch block.

@Test
public void sendGift_throwsException_whenGiftIsNuclearBomb() {
	try {
		service.sendGift(new NuclearBomb());
	} catch (Exception e) {
		assertEquals("Cannot send nuclear bomb as a gift", e.getMessage());
	}
}

#java