[int-to-short] add intToShort()
This commit is contained in:
parent
809460c99d
commit
7b3b52c224
@ -1,6 +1,7 @@
|
|||||||
package com.baeldung.inttoshort;
|
package com.baeldung.inttoshort;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
@ -33,4 +34,22 @@ class ConvertIntToShortUnitTest {
|
|||||||
assertEquals(-31616, result);
|
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));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
Loading…
x
Reference in New Issue
Block a user