javajunityear2038

How to make this Year-2038-problem junit test work as expected


I am writing some code that will stop working after 19 January 2038 because of the Year_2038_problem when java Date overflows so i thougt i could create a junit test that starts failing in 2036 to give me 2 years time to fix it.

To create a failing test first i added 25 years and was surprised that the test did not fail.

@Test
public void warn2038Overflow() {
    Calendar c = Calendar.getInstance();
    c.add(Calendar.YEAR, 25);

    // today is 2019 plus 25 years becomes 2044 which should overflow
    assertEquals("No calendar overflow", true,
            c.getTimeInMillis() > 0l);
}

Any clues why this does not fail?

I am using Android-Studio-3.4.1 with java-1.8.0_152 (64 bit) with 'junit:junit:4.12' and 'androidx.test:runner:1.1.0'


Solution

  • The Year-2038-problem happens when you store the number of epoch seconds in a signed 32 bit integer (which will overflow in 2038).

    The code you are using stores the number of milliseconds in a signed 64 bit integer. That will still work fine for a while.