Hi everybody, I have a stupid question about the kotlin test. How to assert a nullable object nonNull and make it type safe.
I have tried to use
kotlin-test
assertNotNull
to assert an object non null, but finally in the following codes, I still have to use
!!
to convert it to non null value, if possible use some assert to convert it non null safely?
Copy code
class MyTest{
var result: XXX? = null
fun test() {
//...
// saving data into db and got the result
assertNotNull(result)
result.someProperty // if possible use this directly, with type cast to none null using !!
}
}
a
agrosner
04/22/2024, 10:42 AM
Use a val
agrosner
04/22/2024, 10:42 AM
Or assign it one
x
xoangon
04/23/2024, 6:39 AM
This happens because between the call to
assertNotNull(result)
and
result.someProperty
, the value of
result
could be modified from another thread.
You can use an scope function like
let
, that will guarantee that the value hasn't been mutated in that scope:
Copy code
class MyTest{
var result: XXX? = null
fun test() {
//...
// saving data into db and got the result
result?.let { result ->
result.someProperty
}
}
}