Lubię myśleć w kategoriach przypadków testowych. Jakie wartości dla beginDate
i endDate
spowodują, że taka metoda zwróci wartość true lub false?
Na przykład, jeśli są w tym samym roku? Być może obie wartości są po tej samej stronie 29 lutego, lub obejmują je.
Co, jeśli są w różnych latach? Co, jeśli te lata sąsiadują ze sobą lub czy są inne lata pomiędzy? Być może żaden z upływających lat nie jest nawet latami przestępnymi.
Co można wtedy zrobić w tego rodzaju scenariuszu składa się przykłady tych przypadków, a następnie napisać metodę, dostosowując go, aż wszystkie dowody przeminą.
Poniżej przedstawiono podejście, które można zastosować. Możesz dodać przypadki, w których beginDate
i/lub maturity
wylądują w dniu przestępnym.
public class Q26403911 {
@Test
public void testContainsLeapYear() throws Exception {
Assert.assertTrue(isContainsLeapYear(LocalDate.of(1984, 2, 28), LocalDate.of(1984, 3, 1)));
Assert.assertFalse(isContainsLeapYear(LocalDate.of(1985, 2, 28), LocalDate.of(1985, 3, 1)));
Assert.assertFalse(isContainsLeapYear(LocalDate.of(1984, 2, 27), LocalDate.of(1984, 2, 28)));
Assert.assertFalse(isContainsLeapYear(LocalDate.of(1984, 3, 1), LocalDate.of(1984, 3, 2)));
Assert.assertTrue(isContainsLeapYear(LocalDate.of(1984, 2, 28), LocalDate.of(1985, 3, 1)));
Assert.assertTrue(isContainsLeapYear(LocalDate.of(1983, 3, 1), LocalDate.of(1984, 3, 1)));
Assert.assertFalse(isContainsLeapYear(LocalDate.of(1984, 3, 1), LocalDate.of(1985, 3, 1)));
Assert.assertFalse(isContainsLeapYear(LocalDate.of(1983, 2, 28), LocalDate.of(1984, 2, 28)));
Assert.assertTrue(isContainsLeapYear(LocalDate.of(1983, 3, 1), LocalDate.of(1985, 2, 28)));
Assert.assertFalse(isContainsLeapYear(LocalDate.of(1985, 3, 1), LocalDate.of(1987, 2, 28)));
}
public boolean isContainsLeapYear(LocalDate beginDate, LocalDate maturity) {
if (beginDate.getYear() == maturity.getYear())
{
if (!Year.isLeap(beginDate.getYear()))
{
return false;
}
if (maturity.isBefore(LocalDate.of(beginDate.getYear(), Month.FEBRUARY, 29)))
{
return false;
}
if (beginDate.isAfter(LocalDate.of(maturity.getYear(), Month.FEBRUARY, 29)))
{
return false;
}
return true;
}
else if (Year.isLeap(beginDate.getYear())
&& !beginDate.isAfter(LocalDate.of(beginDate.getYear(), Month.FEBRUARY, 29)))
{
return true;
}
else if (Year.isLeap(maturity.getYear())
&& !maturity.isBefore(LocalDate.of(maturity.getYear(), Month.FEBRUARY, 29)))
{
return true;
}
else
{
for (int year = beginDate.getYear() + 1; year < maturity.getYear(); year++)
{
if (Year.isLeap(year))
{
return true;
}
}
}
return false;
}
}
Wystarczy sprawdzić datę ostatniej Lut miesiąca – Roshan
jest to czas Joda lub Java 8 czas api pytanie? Odpowiedź może być inna ... – assylias
@assylias Java 8. Dzięki :-) – YvesHendseth