[int-to-short] add intToShort()

This commit is contained in:
Kai.Yuan 2024-04-24 21:28:19 +02:00
parent 809460c99d
commit 7b3b52c224
1 changed files with 19 additions and 0 deletions

View File

@ -1,6 +1,7 @@
package com.baeldung.inttoshort;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
@ -33,4 +34,22 @@ class ConvertIntToShortUnitTest {
assertEquals(-31616, result);
}
short intToShort(int i) {
if (i < Short.MIN_VALUE || i > Short.MAX_VALUE) {
throw new IllegalArgumentException("Int is out of short range");
}
return (short) i;
}
@Test
void whenCheckShortRangeBeforeCasting_thenGetExpectedResult() {
short expected = 42;
int int42 = 42;
assertEquals(expected, intToShort(int42));
int oneMillion = 1_000_000;
assertThrows(IllegalArgumentException.class, () -> intToShort(oneMillion));
}
}