summaryrefslogtreecommitdiff
path: root/formats/json/jvmTest/src/kotlinx/serialization/features/ContextualSerializationOnFileTest.kt
blob: a190a48371b508dc094fc8d13b7c219fd671c7c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
 * Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

// TODO: Move to common tests after https://youtrack.jetbrains.com/issue/KT-28927 is fixed

@file:UseContextualSerialization(Int::class, IntHolder::class)

package kotlinx.serialization.features

import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import kotlin.test.*

@Serializable
data class Carrier3(
    val a: IntHolder,
    val i: Int,
    val nullable: Int?,
    val nullableIntHolder: IntHolder?,
    val nullableIntList: List<Int?> = emptyList(),
    val nullableIntHolderNullableList: List<IntHolder?>? = null
)

class ContextualSerializationOnFileTest {
    val module = SerializersModule {
        contextual(DividingIntSerializer)
        contextual(MultiplyingIntHolderSerializer)
    }
    val json = Json { serializersModule = module; encodeDefaults = true }

    @Test
    fun testOnFile() {
        val str = json.encodeToString(Carrier3.serializer(), Carrier3(IntHolder(42), 8, 8, IntHolder(42)))
        assertEquals(
            """{"a":84,"i":4,"nullable":4,"nullableIntHolder":84,"nullableIntList":[],"nullableIntHolderNullableList":null}""",
            str
        )
    }
}