0

I'm practicing unit testing on the methods of the Java Period class. The method minusDays looks like this:

public Period minusDays(long daysToSubtract) {
    return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract));

My unit test looks like this:

@Test
public void testMinusDays ()
{
Period x = Period.of(1,1,2);
Period y = Period.of(1,1,1);

Assert.assertEquals(y, x.minusDays(1));
}

And the problem is I'm getting 50% branch coverage and don't know which parts of the if else I'm testing because I can't follow it.

Tom
  • 16,842
  • 17
  • 45
  • 54
Dr NoName
  • 1
  • 3
  • http://stackoverflow.com/questions/33536168/test-case-for-100-branch-coverage-with-no-fault ? – Suresh Atta Nov 06 '15 at 09:32
  • Please don't "destroy" your question if it was solved. Just accept the answer which helped you to solve the problem. Or write an answer yourself if none of the current answer helped. – Tom Nov 06 '15 at 23:24

2 Answers2

3

First Step: If ? : is too confusing, replace it with an equal if condition:

public Period minusDays(long daysToSubtract) {
    if (daysToSubtract == Long.MIN_VALUE)  {
        return plusDays(Long.MAX_VALUE).plusDays(1);
    }
    return plusDays(-daysToSubtract);
}

And now you know what you are missing. You are tesing for daysToSubtract == 1, but not the possibility daysToSubtract == Long.MIN_VALUE, in other words you are only testing one one of two cases, which makes 50%.

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58
  • Even without improving the code readability, by simple logic it's impossible to cover all branches with only one test being performed. If you have two branches you need two tests. – Vitor Santos Nov 06 '15 at 11:12
  • 1
    True, but to me, it seemed that the main problem was, that Dr NoName missed the simple fact that there actually were two branches, so improving the readability might help, esp. for users who are not that familiar with the ? : statement. – Florian Schaetz Nov 06 '15 at 11:27
1

you have to write a test with x.minusDay(Long.MIN_VALUE) and a test with another value. after that you should have 100%

Si mo
  • 969
  • 9
  • 24