In una struttura notturna di Jenkins, uno dei nostri test è fallito alle 2:00:12 del mattino. Dopo un po 'di tempo per il debug e la modifica del tempo di sistema del mio computer, ero molto confuso. Poi ho scritto il seguente test (simulando il problema), che fallisce, ma non riesco a capire perché. Ho provato Google, ma non ho trovato nulla di simile.
Qualcuno può spiegare perché l'ultima affermazione fallisce?Confusione test fallita - ora legale
@Test
public void testFirstBeforeSecond_atDayLightSavingTime() throws ParseException {
Date first = new SimpleDateFormat("dd-MM-yyyy HH:mm").parse("25-10-2015 00:59");
Date second = new SimpleDateFormat("dd-MM-yyyy HH:mm").parse("25-10-2015 01:01");
assertThat(first.before(second), is(true)); // Ok, as expected
first = add(first, Calendar.HOUR_OF_DAY, 2);
second = add(second, Calendar.HOUR_OF_DAY, 2);
assertThat(first.before(second), is(true)); // Ok, as expected
first = add(first, Calendar.DAY_OF_YEAR, 2);
second = add(second, Calendar.DAY_OF_YEAR, 2);
assertThat(first.before(second), is(true)); // Fails?
}
private Date add(Date date, int field, int amount) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Brussels"));
calendar.setTime(date);
calendar.add(field, amount);
return calendar.getTime();
}
(A Bruxelles il fuso orario, l'ora legale è concluso il 25-10-15 alle 3 del mattino. L'orologio poi saltò indietro di un'ora.)
Non si definisce mai un fuso orario! Pertanto, su qualsiasi dispositivo che esegue questo codice viene utilizzata l'impostazione predefinita del fuso orario del sistema host. Il tuo computer locale è normalmente in esecuzione in ora locale e server spesso in UTC. Hai pensato a questo? –
Possibilmente correlato a http://stackoverflow.com/questions/13611108/problems-with-java-daylight-savings-time – dkatzel
@ReneM. Il fuso orario è impostato nel metodo privato 'add':' calendar.setTimeZone (TimeZone.getTimeZone ("Europe/Brussels")); ' – Manu