Add property delegate tests

This commit is contained in:
Shadowfacts 2019-06-25 22:06:29 -04:00
parent 4d1fb68c89
commit 260b1eafc3
Signed by: shadowfacts
GPG Key ID: 94A5AB95422746E5
3 changed files with 71 additions and 0 deletions

View File

@ -8,6 +8,9 @@ import kotlin.reflect.KProperty
class ResettableLazyProperty<Value>(val initializer: () -> Value) { class ResettableLazyProperty<Value>(val initializer: () -> Value) {
var value: Value? = null var value: Value? = null
val isInitialized: Boolean
get() = value != null
operator fun getValue(thisRef: Any, property: KProperty<*>): Value { operator fun getValue(thisRef: Any, property: KProperty<*>): Value {
if (value == null) { if (value == null) {
value = initializer() value = initializer()

View File

@ -0,0 +1,33 @@
package net.shadowfacts.cacao.util.properties
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import java.util.concurrent.CompletableFuture
/**
* @author shadowfacts
*/
class ObservableLateInitPropertyTests {
class MyClass(callback: (String) -> Unit) {
val delegate = ObservableLateInitProperty(callback)
var prop by delegate
}
@Test
fun testObservation() {
val future = CompletableFuture<String>()
val obj = MyClass { future.complete(it) }
obj.prop = "test"
assertEquals("test", future.getNow(null))
}
@Test
fun testIsInitialized() {
val obj = MyClass {}
assertFalse(obj.delegate.isInitialized)
obj.prop = "test"
assertTrue(obj.delegate.isInitialized)
}
}

View File

@ -0,0 +1,35 @@
package net.shadowfacts.cacao.util.properties
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
/**
* @author shadowfacts
*/
class ResettableLazyPropertyTests {
class MyClass {
var iteration = 1
val delegate = ResettableLazyProperty { "test ${iteration++}" }
val prop by delegate
}
@Test
fun testResets() {
val obj = MyClass()
assertEquals("test 1", obj.prop)
obj.delegate.reset()
assertEquals("test 2", obj.prop)
assertEquals("test 2", obj.prop)
}
@Test
fun testIsInitialized() {
val obj = MyClass()
assertFalse(obj.delegate.isInitialized)
assertEquals("test 1", obj.prop)
assertTrue(obj.delegate.isInitialized)
obj.delegate.reset()
assertFalse(obj.delegate.isInitialized)
}
}