1

I have a problem in hitting the yearsToSubtract == Long.MIN_VALUE branch when the value of yearsToSubtract is Long.MIN_VALUE.

public Period minusYears(long yearsToSubtract) {
    return (yearsToSubtract == Long.MIN_VALUE ?plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
}

public Period plusYears(long yearsToAdd) {
     if (yearsToAdd == 0) {
        return this;
    }
    return create(Math.toIntExact(Math.addExact(years, yearsToAdd)), months, days);
}

this is my plusYears Function, my create function is just a getter function which sets the value of years, Months and Days

this is my Test case for covering the branch when the value of yearsToSubtract is Long.MIN_VALUE

   @Test
    public void testIfMinusYears() {

    Period p = Period.of(1, 1, 1);


    try {
        p.minusYears(Long.MIN_VALUE);
    } catch (ArithmeticException e) {

    }
}

This is my test case to hit the other branch when yearsToSubtract is a value which is not equal to Long.MIN_VALUE

    @Test
public void testMinusYears() {
    Period p = Period.of(0, 0, 0);

    p.minusYears(-100);

}

of(years, Months, days) is a function which sets the values of Year, Month and Days

In the Picture it says I am missing a branch in the minusYears() Method which is when yearstoSubtract == Long.MIN_VALUE

can someone please tell me how to hit that branch, this is for an assignment in my class, I have tried in all possible ways, but wasn't able to figure out how to hit that branch.

Thanks

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
Adithya
  • 241
  • 3
  • 16
  • Do I understand correctly that for your class you are writing a unit test for `java.time.Period`? Just asking to be sure I understand. – Ole V.V. Nov 11 '17 at 18:26
  • A guess: for your branch to be considered covered, you must be able to check that you get the expected result. Since your test generates an `ArithmeticException` (that you swallow, naughty), you don’t get to test the result. If this is a sufficient explanation, you may try `Period p = Period.of(-5, 1, 1);` instead. – Ole V.V. Nov 11 '17 at 18:44
  • Thanks for the comment @Ole V.V, I have tried the approach you have mentioned, but the problem is it only covers one branch, but the other branch where the integer overflow occurs is not getting covered. – Adithya Nov 12 '17 at 19:06

0 Answers0