Lazy made serializable.

This commit is contained in:
Ilya Gorbunov
2015-06-16 18:35:33 +03:00
parent bfdb200cc7
commit ecd131a7a1
4 changed files with 112 additions and 15 deletions
@@ -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
}
}
+45
View File
@@ -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)
}
}