From 8ac53f70c4ba2ef139e1acfcbcbf647950a2df25 Mon Sep 17 00:00:00 2001 From: Kacper Date: Mon, 27 Aug 2018 22:21:33 +0200 Subject: [PATCH] Optional or else throw (#5088) * Throw and throws in Java * BAEL-2122 | throw exception in optional * BAEL-2122 | optional orelsethrow * fix test --- .../PersonRepositoryUnitTest.java | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/throwsexception/PersonRepositoryUnitTest.java b/core-java/src/test/java/com/baeldung/throwsexception/PersonRepositoryUnitTest.java index 0d1859fb1a..3749ce10d0 100644 --- a/core-java/src/test/java/com/baeldung/throwsexception/PersonRepositoryUnitTest.java +++ b/core-java/src/test/java/com/baeldung/throwsexception/PersonRepositoryUnitTest.java @@ -13,21 +13,31 @@ public class PersonRepositoryUnitTest { PersonRepository personRepository = new PersonRepository(); @Test - public void whenIdIsNull_thenExceptionIsThrown() throws Exception { - assertThrows(Exception.class, + public void whenIdIsNull_thenExceptionIsThrown() { + assertThrows(IllegalArgumentException.class, () -> Optional .ofNullable(personRepository.findNameById(null)) - .orElseThrow(Exception::new)); + .orElseThrow(IllegalArgumentException::new)); } @Test - public void whenIdIsNonNull_thenNoExceptionIsThrown() throws Exception { + public void whenIdIsNonNull_thenNoExceptionIsThrown() { assertAll( () -> Optional .ofNullable(personRepository.findNameById("id")) - .orElseThrow(Exception::new)); + .orElseThrow(RuntimeException::new)); + } + + @Test + public void whenIdNonNull_thenReturnsNameUpperCase() { + String name = Optional + .ofNullable(personRepository.findNameById("id")) + .map(String::toUpperCase) + .orElseThrow(RuntimeException::new); + + assertEquals("NAME", name); } @Test