androidunit-testingandroid-studiothreetenbp

Android ThreeTen ABP library not working in unit tests (ZoneRulesException)


When I attempt to use Jake Wharton's Android ThreeTen ABP library, in unit tests, I get an exception:

org.threeten.bp.zone.ZoneRulesException: No time-zone data files registered

This question explains that init may have not been called, but how do I do this in a unit test?


Solution

  • This exception is caused because AndroidThreeTen.init has not been called with a context. Local unit tests do not have an Application or a Context which are required for the Android Threeten ABP to load timezone information.

    For unit tests, you can use the regular ThreeTen BP which is not designed for Android. It can load the timezone info without an Android context. None of your imports will need to change.

    Add the additional threeten library to your gradle file, using the testImplementation command.

    implementation "com.jakewharton.threetenabp:threetenabp:1.2.1"
    testImplementation "org.threeten:threetenbp:1.4.0"
    

    Note that the two version numbers do not coincide.