1+ package com .baeldung .booleantoint ;
2+
3+ import static org .junit .jupiter .api .Assertions .assertFalse ;
4+ import static org .junit .jupiter .api .Assertions .assertThrows ;
5+ import static org .junit .jupiter .api .Assertions .assertTrue ;
6+
7+ import org .apache .commons .lang3 .BooleanUtils ;
8+ import org .junit .jupiter .api .Test ;
9+
10+ public class IntToBooleanUnitTest {
11+
12+ boolean intToBoolean (int theInt ) {
13+ return theInt > 0 ;
14+ }
15+
16+ boolean intToBooleanWithThrowing (int theInt ) {
17+ if (theInt == 1 ) {
18+ return true ;
19+ }
20+ if (theInt == 0 ) {
21+ return false ;
22+ }
23+ throw new IllegalArgumentException ("Only 0 or 1 is allowed." );
24+ }
25+
26+ @ Test
27+ void whenUsingBooleanExpression_thenGetExpectedResult () {
28+ assertTrue (intToBoolean (42 ));
29+ assertFalse (intToBoolean (0 ));
30+ assertFalse (intToBoolean (-42 ));
31+ }
32+
33+ @ Test
34+ void whenUsingIfBooleanExpression_thenGetExpectedResult () {
35+ assertTrue (intToBooleanWithThrowing (1 ));
36+ assertFalse (intToBooleanWithThrowing (0 ));
37+ assertThrows (IllegalArgumentException .class , () -> intToBooleanWithThrowing (42 ));
38+ assertThrows (IllegalArgumentException .class , () -> intToBooleanWithThrowing (-42 ));
39+ }
40+
41+ @ Test
42+ void whenUsingBooleanUtilsToBoolean_thenGetExpectedResult () {
43+ // calling BooleanUtils.toBoolean(int value)
44+ assertTrue (BooleanUtils .toBoolean (1 ));
45+ assertFalse (BooleanUtils .toBoolean (0 ));
46+ assertTrue (BooleanUtils .toBoolean (42 ));
47+ assertTrue (BooleanUtils .toBoolean (-42 ));
48+
49+ // calling BooleanUtils.toBoolean(int value, int trueValue, int falseValue)
50+ int trueValue = 1 ;
51+ int falseValue = 0 ;
52+
53+ assertTrue (BooleanUtils .toBoolean (1 , trueValue , falseValue ));
54+ assertFalse (BooleanUtils .toBoolean (0 , trueValue , falseValue ));
55+ assertThrows (IllegalArgumentException .class , () -> BooleanUtils .toBoolean (42 , trueValue , falseValue ));
56+ assertThrows (IllegalArgumentException .class , () -> BooleanUtils .toBoolean (-42 , trueValue , falseValue ));
57+ }
58+
59+ }
0 commit comments