Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: unit test assert object after gson

Tags:

junit

gson

kotlin

I have JUnit test like that:

Test fun testCategoriesLoading() {
    val subscriber = TestSubscriber<List<ACategory>>()
    service.categories().subscribe(subscriber)

    subscriber.awaitTerminalEvent()

    subscriber.assertNoErrors()
}

service is Retrofit, that uses GsonConverter to deserialize json into

data class ACategory(val id: String, val title: String, val parentId: String?, val hasChildren: Boolean)

instances.

Test is passing, even if ACategory filled with id = null, title = null etc.

So, as far as i know, gson using reflection, and kotlin lazily resolves this nullability constraints on first access.

Is there any way to force this resolve? Some good-looking solution without direct access to fields manually? I really don't want to write every assert by hand.

like image 624
Dmitriy Voronin Avatar asked Nov 09 '22 10:11

Dmitriy Voronin


1 Answers

You could use the new Kotlin reflection. If you have an instance of ACategory, call

ACategory::class.memberProperties
        .filter { !it.returnType.isMarkedNullable }
        .forEach {
            assertNotNull(it.get(aCategory))
        }

to access all properties that are marked as not nullable and assert they're not null. Make sure, you have the reflection lib on the classpath.

Make sure you're using M14.

like image 133
Kirill Rakhman Avatar answered Nov 17 '22 06:11

Kirill Rakhman