I want to test a `ViewModel` using `BehaviorSpec`,...
# kotest
l
I want to test a
ViewModel
using
BehaviorSpec
, but I want the viewmodel to be a completely new instance for every leaf test (i.e. I want every
Given { When { Then
be an independent test). When using the default isolation mode (
SingleInstance
) is it possible to somehow reset the ViewModel for every leaf test? Or do I have to switch to the isolation mode
InstancePerTest
? I tried
InstancePerLeaf
and it seemed like the
Given/When
blocks initializations were not taken over correctly into their nested
Then
blocks.
InstancePerTest
works correctly for me, but I wanted to take advantage of faster test execution without having to instantiate the class for every test.
t
Most highly not the correct way, but I cheated using:
Copy code
fun <V> Spec.varBeforeTest(
    bouwer :  () -> V
) = object : ReadWriteProperty<Nothing?,V> {
    var waarde : V? = null
    init {
        beforeTest {
            waarde = bouwer()
        }
    }
    override fun getValue(thisRef: Nothing?, property: KProperty<*>): V = waarde as V

    override fun setValue(thisRef: Nothing?, property: KProperty<*>, value: V) {
        waarde = value
    }

}
👍 1
e
I think this is basically asking for the same thing Leo talked about a few days ago. Would it be ok to base a PR on your code @tieskedh? If you'd like you're ofc welcome to contribute it directly yourself 🙂
t
@Emil Kantis haha, of course you can. But, there might be better implementations, for example the considerations: 1. Make it lazy: delay to getter 2. Use DSL : something like
awaitclose
can be handy. can of course also be another function.