How would you write assertThat(foo, instanceOf(Bar.class)) with Kotlin?
Seems that it does not like the .class
I would like to go for an assertion which is a bit more "precise" than just an assertTrue(foo is Bar) if possible
How would you write assertThat(foo, instanceOf(Bar.class)) with Kotlin?
Seems that it does not like the .class
I would like to go for an assertion which is a bit more "precise" than just an assertTrue(foo is Bar) if possible
You could use Atrium (https://atriumlib.org) and write the following
assertThat(foo).isA<Bar>{}
And in case you want to assert more about foo, say Bar has a val baz: Int, then you can write the following
assertThat(foo).isA<Bar> {
property(subject::baz).isSmallerThan(41)
}
I would like to go for an assertion which is a bit more "precise" than just an assertTrue(foo is Bar) if possible
This is a code smell in the making.
The (ridiculously named) "Liskov substitution principle" of good software design recommends not depending on a concrete implementation: a subtype should always be able to replace a type with the client code using it not caring / being affected.
If you are depending on some special functionality of the subtype, use the subtype after is.
If the subtype is dynamic (anonymous class?) or the name of the type is not in the namespace of the test code (private / internal class?), and/or you need to assert a base class instance was provided, assert something about the functionality of the subtype that the supertype does not provide (or vice versa).
If there is no such functionality that has a publicly observable effect, then reflect on what you are really trying to test.
The main exception I see is when
assert something about the functionality of the subtype that the supertype does not provide (or vice versa).
would be extremely slow or otherwise difficult to run (e.g., messes up state).
You can use assertInstanceOf doc here
And it become as simple as :
import org.junit.jupiter.api.Assertions.assertInstanceOf
assertInstanceOf(Bar::class.java, foo)