Reputation: 9
Hello I have a problem testing this, as I get an error that the testing is not right, can you guys explain why and what are the mistakes?
public void addDays(int x) {
int y = year;
day = day + x;
if (day > 31) {
day = day - 31;
addMonths(1);
} else if (day >= 29 && month == 2 && (isLeapYear(y))) {
day = day - 29;
addMonths(1);
} else if (day >= 28 && month == 2 && !(isLeapYear(y))) {
{
day = day - 28;
addMonths(1);
}
}
}
and this is my test for this method (Im using Netbeans).
@Test
public void testAddDays() {
Date z = new Date(31,11,2013);
z.addDays(3);
assertEquals(3, z.getDay());
}
@Test
public void testAddDays1() {
Date z = new Date(28,2,2016);
z.addDays(3);
assertEquals(2, z.getDay());
}
@Test
public void testAddDays2() {
Date z = new Date(29,2,2014);
z.addDays(2);
assertEquals(3, z.getDay());
}
I would like to know where are my mistakes and how can I fix them
Upvotes: 0
Views: 80
Reputation: 493
One solution would be to replace your custom-built date arithmetic with the java.util
classes Date
and Calendar
, unless there's a reason not to use them (such as this being a date calculation exercise), since those utility classes are standard and well-tested.
For consistency with the Calendar
class, I'd recommend a (year, month, date) format instead of your (date, month, year). That will make it more convenient to test your code against java.util
results.
So, to look at your test cases, using your Date(date, month, year)
format, on the assumption that you're not allowed to use java.util
:
One obvious bug in your addDays(int x)
method is that it doesn't test for x
greater than one month. If you're not worried that the code will be slow for large x
, you could iterate through all the months with something like this:
if (x < 0) {
subtractDays(x);
return;
}
day += x;
while (day > 0) {
int daysThisMonth;
switch (month) {
case 2: daysThisMonth = isLeapYear() ? 29 : 28; break;
case 4: case 6: case 9: case 11: daysThisMonth = 30; break;
case 1: case 3: case 5: case 7: case 8: case 10: case 12: daysThisMonth = 31; break;
default: // ERROR.
}
addMonths(1);
day -= daysThisMonth;
}
Note that this code depends on addMonths()
ignoring day
, which is a code maintenance problem. I'm assuming there's also a subtractDays()
method; if not, you'll need to revise your addDays()
to allow for negative x
.
There may also be problems in your constructor; it needs to test for handle dates that do not conform with calendar standards.
Upvotes: 1