Skip to content

Commit 9b343be

Browse files
kacperkozamaibin
authored andcommitted
BAEL-2122 Optional or else throw (eugenp#5047)
* Throw and throws in Java * BAEL-2122 | throw exception in optional * BAEL-2122 | optional orelsethrow
1 parent 2779300 commit 9b343be

2 files changed

Lines changed: 12 additions & 1 deletion

File tree

‎core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public class PersonRepository {
88

99
@Nullable
1010
public String findNameById(String id) {
11-
return id == null ? null : "example-name";
11+
return id == null ? null : "Name";
1212
}
1313

1414
public List<String> findAll() throws SQLException {

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import java.util.Optional;
66

7+
import static org.junit.Assert.assertEquals;
78
import static org.junit.jupiter.api.Assertions.assertAll;
89
import static org.junit.jupiter.api.Assertions.assertThrows;
910

@@ -29,4 +30,14 @@ public void whenIdIsNonNull_thenNoExceptionIsThrown() throws Exception {
2930
.orElseThrow(Exception::new));
3031
}
3132

33+
@Test
34+
public void whenIdIsNonNull_thenShouldReturnNameUpperCase() throws Exception {
35+
String name = Optional
36+
.ofNullable(personRepository.findNameById("id"))
37+
.map(String::toUpperCase)
38+
.orElseThrow(Exception::new);
39+
40+
assertEquals("NAME", name);
41+
}
42+
3243
}

0 commit comments

Comments
 (0)