|
| 1 | +package com.baeldung.jspecify; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 4 | +import static org.junit.jupiter.api.Assertions.assertThrows; |
| 5 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 6 | + |
| 7 | +import java.util.Objects; |
| 8 | +import java.util.Optional; |
| 9 | + |
| 10 | +import org.jspecify.annotations.Nullable; |
| 11 | +import org.junit.jupiter.api.Test; |
| 12 | + |
| 13 | +public class JspecifyNullSafetyTest { |
| 14 | + |
| 15 | + @Test |
| 16 | + void givenKnownUserId_whenFindNickname_thenReturnsOptionalWithValue() { |
| 17 | + Optional<String> nickname = findNickname("user123"); |
| 18 | + |
| 19 | + assertTrue(nickname.isPresent()); |
| 20 | + assertEquals("CoolUser", nickname.get()); |
| 21 | + } |
| 22 | + |
| 23 | + @Test |
| 24 | + void givenUnknownUserId_whenFindNickname_thenReturnsEmptyOptional() { |
| 25 | + Optional<String> nickname = findNickname("unknownUser"); |
| 26 | + |
| 27 | + assertTrue(nickname.isEmpty()); |
| 28 | + } |
| 29 | + |
| 30 | + @Test |
| 31 | + void givenNonNullArgument_whenValidate_thenDoesNotThrowException() { |
| 32 | + String result = processNickname("CoolUser"); |
| 33 | + assertEquals("Processed: CoolUser", result); |
| 34 | + } |
| 35 | + |
| 36 | + @Test |
| 37 | + void givenNullArgument_whenValidate_thenThrowsNullPointerException() { |
| 38 | + assertThrows(NullPointerException.class, () -> processNickname(null)); |
| 39 | + } |
| 40 | + |
| 41 | + @Test |
| 42 | + void givenUnknownUserId_whenFindNicknameOrNull_thenReturnsNull() { |
| 43 | + String nickname = findNicknameOrNull("unknownUser"); |
| 44 | + assertTrue(nickname == null); |
| 45 | + } |
| 46 | + |
| 47 | + @Test |
| 48 | + void givenNullableMethodResult_whenWrappedInOptional_thenHandledSafely() { |
| 49 | + String nickname = findNicknameOrNull("unknownUser"); |
| 50 | + Optional<String> safeNickname = Optional.ofNullable(nickname); |
| 51 | + |
| 52 | + assertTrue(safeNickname.isEmpty()); |
| 53 | + } |
| 54 | + |
| 55 | + private Optional<String> findNickname(String userId) { |
| 56 | + if ("user123".equals(userId)) { |
| 57 | + return Optional.of("CoolUser"); |
| 58 | + } else { |
| 59 | + return Optional.empty(); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + @Nullable |
| 64 | + private String findNicknameOrNull(String userId) { |
| 65 | + if ("user123".equals(userId)) { |
| 66 | + return "CoolUser"; |
| 67 | + } else { |
| 68 | + return null; |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + private String processNickname(String nickname) { |
| 73 | + Objects.requireNonNull(nickname, "Nickname must not be null"); |
| 74 | + return "Processed: " + nickname; |
| 75 | + } |
| 76 | +} |
0 commit comments