-
Notifications
You must be signed in to change notification settings - Fork 636
/
Copy pathPolymorphicSealedChildTest.kt
65 lines (55 loc) · 1.65 KB
/
PolymorphicSealedChildTest.kt
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.features
import kotlinx.serialization.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.*
import kotlinx.serialization.test.assertStringFormAndRestored
import kotlin.test.Test
class PolymorphicSealedChildTest {
@Serializable
data class FooHolder(
val someMetadata: Int,
val payload: List<@Polymorphic FooBase>
)
@Serializable
abstract class FooBase
@Serializable
@SerialName("Foo")
sealed class Foo: FooBase() {
@Serializable
@SerialName("Bar")
data class Bar(val bar: Int) : Foo()
@Serializable
@SerialName("Baz")
data class Baz(val baz: String) : Foo()
}
val sealedModule = SerializersModule {
polymorphic(FooBase::class) {
subclassesOf<Foo>()
}
}
val json = Json { serializersModule = sealedModule }
@Test
fun testSaveSealedClassesList() {
assertStringFormAndRestored(
"""{"someMetadata":42,"payload":[
|{"type":"Bar","bar":1},
|{"type":"Baz","baz":"2"}]}""".trimMargin().replace("\n", ""),
FooHolder(42, listOf(Foo.Bar(1), Foo.Baz("2"))),
FooHolder.serializer(),
json,
printResult = true
)
}
@Test
fun testCanSerializeSealedClassPolymorphicallyOnTopLevel() {
assertStringFormAndRestored(
"""{"type":"Bar","bar":1}""",
Foo.Bar(1),
PolymorphicSerializer(FooBase::class),
json
)
}
}