Issue
I want to coverage all of if branches. I create a dumb class with multiple if...else, and test it with all branches conditions to test coverage. The Eclipse reports abount 1 of 4 branches missed and 2 of 4 branches missed. But why it happens? Where are the missed branches?
The class with if...else conditions:
public class Coverage {
public void function(Object o1, Object o2) {
if (o1 == null && o2 == null) {
System.out.println(o1 + " " + o2);
} else if (o1 != null && o2 == null) {
System.out.println(o1 + " " + o2);
} else if (o1 == null && o2 != null) {
System.out.println(o1 + " " + o2);
} else if (o1 != null && o2 != null) {
System.out.println(o1 + " " + o2);
}
}
}
The test:
public class CoverageTest {
Coverage c;
@BeforeEach
public void beforeEach() {
c = new Coverage();
}
@Test
public void testFunction_null_null() {
c.function(null, null);
}
@Test
public void testFunction_object_null() {
c.function(new Object(), null);
}
@Test
public void testFunction_null_object() {
c.function(null, new Object());
}
@Test
public void testFunction_object_object() {
c.function(new Object(), new Object());
}
}
The Eclipse coverage report:
Solution
The missed branches are dead code.
Each of the if conditions consists of two Boolean conditions, resulting in four branches. But only in the first two if conditions all combinations of the Boolean conditions are covered by the test. The last two if statements contain unnecessary conditions that are already handled in previous if statements:
public void function(Object o1, Object o2) {
if (o1 == null && o2 == null) {
System.out.println(o1 + " " + o2);
} else if (o1 != null && o2 == null) {
System.out.println(o1 + " " + o2);
} else if (o1 == null) { // o2 != null (o2 == null is already caught in first if-statement)
System.out.println(o1 + " " + o2);
} else { // o1 != null and o2 != null (everything else is caught in previous if-statements)
System.out.println(o1 + " " + o2);
}
}
Or simplified even further:
public void function(Object o1, Object o2) {
if (o1 == null) {
if (o2 == null) {
System.out.println(o1 + " " + o2);
} else {
System.out.println(o1 + " " + o2);
}
} else {
if (o2 == null) {
System.out.println(o1 + " " + o2);
} else {
System.out.println(o1 + " " + o2);
}
}
}
Answered By - howlger
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.