phil-t
02/14/2022, 12:12 PMnullableThing?.shouldBe(something) // This works
nullableThing?.shouldBeGreaterThan(something). // This doesn't work
If nullableThing is null the safe call stops the assertion from being called, so the tests passes when it shouldn’t.
I found two ways to fix this but neither seem ideal to me:
• Add another assertion to check that the thing isn’t null e.g. nullableThing shouldNotBe null
• Use !!.
instead of ?.
but this gives a null pointer exception when the test fails which could lead to confusion
Is there a better way to deal with assertions on nullable variables?christophsturm
02/14/2022, 12:15 PMval x: String? = "blah"
x.shouldNotBeNull()
x.shouldBe("blah")
christophsturm
02/14/2022, 12:16 PMwasyl
02/14/2022, 12:27 PMnullableThing?.something()
basically impossible to override? It’s compiler that is not calling something
because that’s how ?.
operator works blob thinking upside downchristophsturm
02/14/2022, 12:33 PMRob Elliot
02/14/2022, 12:37 PMshouldBe
on a nullable type. Just use nullableThing.shouldBe(something)
.Rob Elliot
02/14/2022, 12:38 PMval nullableThing: String? = null
nullableThing.shouldBe("not null")
Expected "not null" but actual was null
java.lang.AssertionError: Expected "not null" but actual was null
phil-t
02/14/2022, 1:41 PMphil-t
02/14/2022, 1:49 PMshouldBeGreaterThan
shouldBe
and shouldNotBe
work with nullable variables but shouldBeGreaterThan
doesn’t, that causes this error - Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Int?
phil-t
02/14/2022, 1:51 PMchristophsturm
02/14/2022, 1:58 PMchristophsturm
02/14/2022, 1:59 PMphil-t
02/14/2022, 2:16 PMnull should be > 0
The danger with the way it currently works is that it’s too easy to try to fix the problem by using ?.
and then you have a test that will incorrectly pass when the variable is nullphil-t
02/14/2022, 2:25 PMsam
02/14/2022, 4:14 PMval name: String? = "foo"
name.shouldNotBeNull().shouldHaveLength(3)
sam
02/14/2022, 4:14 PMphil-t
02/14/2022, 4:16 PMMichael Strasser
02/14/2022, 11:32 PMnullableThing?.let {
it shouldBe something
} ?: fail("thing should not be null")