Lazy made serializable.
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
package test.utils
|
||||
|
||||
|
||||
import kotlin.*
|
||||
import kotlin.test.*
|
||||
import java.io.*
|
||||
import org.junit.Test as test
|
||||
|
||||
class LazyJVMTest {
|
||||
|
||||
test fun lazyInitializationForcedOnSerialization() {
|
||||
for(mode in listOf(LazyThreadSafetyMode.SYNCHRONIZED, LazyThreadSafetyMode.NONE)) {
|
||||
val lazy = lazy(mode) { "initialized" }
|
||||
assertFalse(lazy.valueCreated)
|
||||
val lazy2 = serializeAndDeserialize(lazy)
|
||||
assertTrue(lazy.valueCreated)
|
||||
assertTrue(lazy2.valueCreated)
|
||||
assertEquals(lazy.value, lazy2.value)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun serializeAndDeserialize<T>(value: T): T {
|
||||
val outputStream = ByteArrayOutputStream()
|
||||
val objectOutputStream = ObjectOutputStream(outputStream)
|
||||
|
||||
objectOutputStream.writeObject(value)
|
||||
objectOutputStream.close()
|
||||
outputStream.close()
|
||||
|
||||
val inputStream = ByteArrayInputStream(outputStream.toByteArray())
|
||||
val inputObjectStream = ObjectInputStream(inputStream)
|
||||
return inputObjectStream.readObject() as T
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package test.utils
|
||||
|
||||
import kotlin.*
|
||||
import kotlin.test.*
|
||||
import org.junit.Test as test
|
||||
|
||||
class LazyTest {
|
||||
|
||||
test fun initializationCalledOnce() {
|
||||
var callCount = 0
|
||||
val lazyInt = lazy { ++callCount }
|
||||
|
||||
assertEquals(0, callCount)
|
||||
assertEquals(1, lazyInt.value)
|
||||
assertEquals(1, callCount)
|
||||
|
||||
lazyInt.value
|
||||
assertEquals(1, callCount)
|
||||
}
|
||||
|
||||
test fun valueCreated() {
|
||||
var callCount = 0
|
||||
val lazyInt = lazy { ++callCount }
|
||||
|
||||
assertFalse(lazyInt.valueCreated)
|
||||
assertEquals(0, callCount)
|
||||
|
||||
lazyInt.value
|
||||
|
||||
assertTrue(lazyInt.valueCreated)
|
||||
}
|
||||
|
||||
|
||||
test fun lazyToString() {
|
||||
var callCount = 0
|
||||
val lazyInt = lazy { ++callCount }
|
||||
|
||||
assertNotEquals("1", lazyInt.toString())
|
||||
assertEquals(0, callCount)
|
||||
|
||||
assertEquals(1, lazyInt.value)
|
||||
assertEquals("1", lazyInt.toString())
|
||||
assertEquals(1, callCount)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user