Kotest Test Assertions
Kotest is divided into several subprojects that can be used independently. One of these subprojects provides comprehensive assertion and matcher support. It can be used with the Kotest test framework or with other test frameworks such as JUnit or Spock.
The core feature of the assertion module is functions that test state. Kotest calls these types of state assertion functions matchers. There are core matchers and matchers for third-party libraries.
There are also many other utilities for writing tests, such as exception testing, functions that help test non-deterministic code, inspectors for collections, and soft assertions that group assertions.
Various Matchers
For example, to verify that a variable has an expected value, you can use the shouldBe function.
name shouldBe "devkuma"
There are general-purpose matchers such as shouldBe, as well as matchers for many specific scenarios, such as str.shouldHaveLength(10) for testing the length of a string and file.shouldBeDirectory() for testing whether a specific file points to a directory. These functions are provided in both infix and regular forms.
For example, assertions can usually be chained:
"substring".shouldContain("str")
.shouldBeLowerCase()
myImageFile.shouldHaveExtension(".jpg")
.shouldStartWith("https")
There are more than 350 matchers across several modules. Check all matchers here.
Clues
Sometimes a failed assertion may not contain enough information to tell exactly what went wrong.
For example, suppose you verify the following:
user.name shouldNotBe null
If this verification fails, it simply outputs:
<null> should not equal <null>
This is not particularly helpful. You can use clues to add additional context to failure messages.
Inspectors
Inspectors let you test elements in a collection and specify how many elements are expected to pass, such as all, none, or exactly k.
For example, you can check three elements in mylist as follows:
mylist.forExactly(3) {
it.city shouldBe "Chicago"
}
Check inspectors here.
Custom Matchers
You can easily add your own matchers by extending the Matcher<T> interface. Here, T is the type you want to match. Custom matchers can be composed from existing matchers or used completely independently.
See the full working example.