Hi! Is there a more elegant way to assert that an ...
# kotest
o
Hi! Is there a more elegant way to assert that an object is both non-null and assert its contents than this?
d
Copy code
person
  .shouldNotBeNull()
  .name.shouldBe("Donald Duck")
o
Nice, thanks! Quick and easy. 🙂
How would you do it if I want to assert for other fields as well? let?
d
Yep! That's how I tend to do it:
Copy code
person
  .shouldNotBeNull()
  .let{
     it.name.shouldBe("Donald Duck")
     it.someOtherField.shouldBe("foo")
   }
s
or if you want to avoid the it. you can use .apply
either or
o
Ah yes, that makes it even shorter, thanks. 🙂
l
I usually just go person shouldBe Person("Donald Duck", "Foo")
It it's null the test will crash anyway
p
I tend to go with
Copy code
person should { 
    it.shouldNotBeNull()
    it.name shouldBe "Donald Duck"
    it.someOtherField shouldBe "foo"
}
although I’ve always thought
infix fun <T> T.should(matcher: (T) -> Unit) = matcher(this)
would be nicer as
infix fun <T> T.should(matches: T.() -> Unit) = this.matches()