Skip to content

Commit b4aa279

Browse files
shubhi22maibin
authored andcommitted
BALE-2224 Ternary Operator In Java (eugenp#5362)
1 parent 4917686 commit b4aa279

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}

0 commit comments

Comments
 (0)