androidunit-testingthreetenbp

How to initialize ThreeTen Android backport in a Unit test


I use this library for storing date & time related data in my app. When the application starts, AndroidThreeTen is initialized first to function properly. So I want to ask how to initialize it when unit testing? E.g. I want to test using LocalDate, LocalDateTime, etc.

My current way is like this:

class OverviewViewModelTest {

    @Rule
    @JvmField
    val rule = InstantTaskExecutorRule()

    @Before
    fun setup() {
        AndroidThreeTen.init(Application())
    }

    //...
}

But it throws this error:

java.lang.ExceptionInInitializerError
    at org.threeten.bp.ZoneRegion.ofId(ZoneRegion.java:143)
    at org.threeten.bp.ZoneId.of(ZoneId.java:358)
    at org.threeten.bp.ZoneId.of(ZoneId.java:286)
    at org.threeten.bp.ZoneId.systemDefault(ZoneId.java:245)
    at org.threeten.bp.Clock.systemDefaultZone(Clock.java:137)
    at org.threeten.bp.LocalDate.now(LocalDate.java:165)
Caused by: java.lang.RuntimeException: Method getAssets in android.content.ContextWrapper not mocked. See http://g.co/androidstudio/not-mocked for details.
    at android.content.ContextWrapper.getAssets(ContextWrapper.java)
    at com.jakewharton.threetenabp.AssetsZoneRulesInitializer.initializeProviders(AssetsZoneRulesInitializer.java:22)
    at org.threeten.bp.zone.ZoneRulesInitializer.initialize(ZoneRulesInitializer.java:89)
    at org.threeten.bp.zone.ZoneRulesProvider.<clinit>(ZoneRulesProvider.java:82)
    ... 32 more

So how can I get this library to work in unit tests?


Solution

  • Using the latest comment at the GitHub issue, I was able to run the Three Ten Android backport using the Robolectric library. For Kotlin users, do not use the final class. Instead, use the open class.

    In your app's build.gradle, add:

    dependencies {
        // ...
        testImplementation('org.threeten:threetenbp:1.3.8') {
            exclude group: 'com.jakewharton.threetenabp', module: 'threetenabp'
        }
    }
    

    and use this template to write tests using ThreeTenABP:

    @RunWith(RobolectricTestRunner::class)
    open class DateUtilTest {
    
        @Test
        fun testName {
            // Write as normal
        }
    }