Davio
09/26/2024, 10:36 AM@JvmInline
value class Wrapper(value: Int)
Wrapper(1) shouldBe 1
Currently this throws an exception because they have different types.
If shouldBe
is not appropriate (because it would also indicate that 1 shouldBe Wrapper(1)
, maybe a custom extension method such as shouldHaveValue
or something?
Of course, in this case you can easily do Wrapper(1).value shouldBe 1
Alex Kuznetsov
09/27/2024, 12:29 PMshouldHaveValue
makes sense to meDavio
09/27/2024, 1:47 PMinterface Marker<T> {
val value: T
}
@JvmInline
value class Wrapper(override val value: Int) : Marker<Int>
infix fun <T> Marker<T>.shouldHaveValue(expected: T) = this.value shouldBe expected
Wrapper(1) shouldHaveValue 1
Johan
09/27/2024, 2:45 PM@JvmInline
value class Foo(val value: Int)
infix fun Any.shouldHaveValue(expected: Any?) {
require(this::class.isValue) { "Not a value class" }
val actual = if (expected?.let { it::class.isValue } == true) {
this
} else {
this::class.declaredMemberProperties.single().call(this)
}
actual shouldBe expected
}
fun main() {
val foo = Foo(1)
foo shouldHaveValue 1
foo shouldHaveValue Foo(1)
}
Johan
09/27/2024, 2:49 PMinfix fun Any.shouldHaveValue(expected: Any) {
require(this::class.isValue) { "Not a value class" }
require(!expected::class.isValue) { "A value class" }
this::class.declaredMemberProperties.single().call(this) shouldBe expected
}
depending on if you want only
val foo = Foo(1)
foo shouldHaveValue 1
and not the following to work
foo shouldHaveValue Foo(1)
Johan
09/27/2024, 2:54 PMinfix fun Any.shouldHaveValue(expected: Any) {
valueClassValueOrInstance(this) shouldBe valueClassValueOrInstance(expected)
}
private fun Any?.valueClassValueOrInstance(x: Any): Any? {
return when {
this != null && this::class.isValue -> this::class.declaredMemberProperties.single().call(this)
else -> this
}
}
If you want both previous values and the other way around
Foo(1) shouldHaveValue 1
Alex Kuznetsov
09/27/2024, 3:38 PMEmil Kantis
09/28/2024, 7:36 AMfun foo(): Wrapper
, in which case, wouldn't you want to assert that foo() shouldBe Wrapper(1)
? Asserting with shouldHaveValue
would let you swap to another Int-wrapper without the test failing 🤔Emil Kantis
09/28/2024, 7:36 AMDavio
09/28/2024, 8:28 AMshouldHaveAmount
for it.