Skip to content

Commit 8ac53f7

Browse files
kacperkozamaibin
authored andcommitted
Optional or else throw (eugenp#5088)
* Throw and throws in Java * BAEL-2122 | throw exception in optional * BAEL-2122 | optional orelsethrow * fix test
1 parent c209eec commit 8ac53f7

1 file changed

Lines changed: 15 additions & 5 deletions

File tree

‎core-java/src/test/java/com/baeldung/throwsexception/PersonRepositoryUnitTest.java‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,21 +13,31 @@ public class PersonRepositoryUnitTest {
1313
PersonRepository personRepository = new PersonRepository();
1414

1515
@Test
16-
public void whenIdIsNull_thenExceptionIsThrown() throws Exception {
17-
assertThrows(Exception.class,
16+
public void whenIdIsNull_thenExceptionIsThrown() {
17+
assertThrows(IllegalArgumentException.class,
1818
() ->
1919
Optional
2020
.ofNullable(personRepository.findNameById(null))
21-
.orElseThrow(Exception::new));
21+
.orElseThrow(IllegalArgumentException::new));
2222
}
2323

2424
@Test
25-
public void whenIdIsNonNull_thenNoExceptionIsThrown() throws Exception {
25+
public void whenIdIsNonNull_thenNoExceptionIsThrown() {
2626
assertAll(
2727
() ->
2828
Optional
2929
.ofNullable(personRepository.findNameById("id"))
30-
.orElseThrow(Exception::new));
30+
.orElseThrow(RuntimeException::new));
31+
}
32+
33+
@Test
34+
public void whenIdNonNull_thenReturnsNameUpperCase() {
35+
String name = Optional
36+
.ofNullable(personRepository.findNameById("id"))
37+
.map(String::toUpperCase)
38+
.orElseThrow(RuntimeException::new);
39+
40+
assertEquals("NAME", name);
3141
}
3242

3343
@Test

0 commit comments

Comments
 (0)