File tree Expand file tree Collapse file tree
core-java/src/test/java/com/baeldung/ternaryoperator Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .baeldung .ternaryoperator ;
2+
3+ import static org .assertj .core .api .Assertions .assertThat ;
4+ import org .junit .Test ;
5+
6+ public class TernaryOperatorUnitTest {
7+
8+ @ Test
9+ public void givenACondition_whenUsingTernaryOperator_thenItEvaluatesConditionAndReturnsAValue () {
10+ int number = 10 ;
11+ String msg = number > 10 ? "Number is greater than 10" : "Number is less than or equal to 10" ;
12+
13+ assertThat (msg ).isEqualTo ("Number is less than or equal to 10" );
14+ }
15+
16+ @ Test
17+ public void givenATrueCondition_whenUsingTernaryOperator_thenOnlyExpression1IsEvaluated () {
18+ int exp1 = 0 , exp2 = 0 ;
19+ int result = 12 > 10 ? ++exp1 : ++exp2 ;
20+
21+ assertThat (exp1 ).isEqualTo (1 );
22+ assertThat (exp2 ).isEqualTo (0 );
23+ assertThat (result ).isEqualTo (1 );
24+ }
25+
26+ @ Test
27+ public void givenAFalseCondition_whenUsingTernaryOperator_thenOnlyExpression2IsEvaluated () {
28+ int exp1 = 0 , exp2 = 0 ;
29+ int result = 8 > 10 ? ++exp1 : ++exp2 ;
30+
31+ assertThat (exp1 ).isEqualTo (0 );
32+ assertThat (exp2 ).isEqualTo (1 );
33+ assertThat (result ).isEqualTo (1 );
34+ }
35+
36+ @ Test
37+ public void givenANestedCondition_whenUsingTernaryOperator_thenCorrectValueIsReturned () {
38+ int number = 6 ;
39+ String msg = number > 10 ? "Number is greater than 10" : number > 5 ? "Number is greater than 5" : "Number is less than or equal to 5" ;
40+
41+ assertThat (msg ).isEqualTo ("Number is greater than 5" );
42+ }
43+ }
You can’t perform that action at this time.
0 commit comments