Truthish

Using Truthish in Your Tests
Basics
Truthish is a testing API inspired by Google Truth but
rewritten in Kotlin from the ground up, so it can be used in Kotlin
multiplatform projects.
For example, you can write assertThat checks in tests like this:
import com.varabyte.truthish.*
import com.varabyte.truthish.assertions.*
fun isEven(num: Int) = (num % 2) == 0
fun square(num: Int) = (num * num)
@Test
fun testEvenOdd() {
assertThat(isEven(1234)).isTrue()
assertThat(isEven(1235)).isFalse()
}
@Test
fun testSum() {
val nums = listOf(1, 2, 3, 4, 5)
assertThat(nums.sum()).isEqualTo(15)
}
@Test
fun testMap() {
assertThat(listOf(1, 2, 3, 4, 5).map { square(it) })
.containsExactly(1, 4, 9, 16, 25)
.inOrder()
}
@Test
fun customMessage() {
assertWithMessage("Unexpected list size")
.that(listOf(1, 2, 3, 4, 5)).hasSize(5)
}
@Test
fun testDivideByZeroException() {
val ex = assertThrows<ArithmeticException> {
10 / 0
}
assertThat(ex.message).isEqualTo("/ by zero")
}
[!TIP]
Truthish makes heavy use of extension functions. To cover everything you will need, we recommend adding two wildcard
imports to the top of each of your tests (as we did in the above example):
import com.varabyte.truthish.*
import com.varabyte.truthish.assertions.*
If you would like to check multiple assertions at the same time (meaning a failure won’t be reported until all checks
have run), you can use the assertAll function:
val person = Person("Alice", 30)
assertAll {
that(person.name).isEqualTo("Bob")
that(person.age).isEqualTo(45)
}
// The above will assert once, reporting both equality check failures
You can read the Google Truth documentation for why they
believe their fluent approach to assertions is both more readable and produces
cleaner error messages, but let’s break one of the tests above to see a
specific example error message:
@Test
fun testMapButIntentionallyBroken() {
assertThat(listOf(1, 2, 3, 4, 5).map { square(it) })
.containsExactly(1, 4, 9, 15, 26) // <-- Ooops, messed up 16 and 25 here
.inOrder()
}
Output:
A collection did not contain exactly the expected element(s)
Expected exactly all elements from: [ 1, 4, 9, 15, 26 ]
But was : [ 1, 4, 9, 16, 25 ]
Missing : [ 15, 26 ]
Extraneous : [ 16, 25 ]
Advanced
Correspondence
If you need to compare the elements of a collection more loosely than strict equality, you can use a Correspondence.
For example, to check a list of error messages without spelling each one out in full:
assertThat(errors)
.comparingElementsUsing(Correspondence.contains)
.containsExactly("unresolved", "cannot be reassigned")
You can also write your own, and the actual and expected types can differ. For example, to check strings against the
numbers they should parse to:
val parsesTo = Correspondence<String, Int>("parses to") { actual, expected -> actual.toIntOrNull() == expected }
assertThat(listOf("1", "2", "3"))
.comparingElementsUsing(parsesTo)
.containsExactly(1, 2, 3)
Mismatches
When two collections differ, Truthish reports the missing and extraneous elements. If collections are large and/or the
elements have a long toString representation, it can be hard to tell which missing element was meant to be which
extraneous one.
To help with this, Truthish lets you tell it how to pair two related values. If a missing value and an extraneous
value can be paired, they will be converted into a mismatch instead.
For example, imagine you had a class representing users:
data class User(val id: Int, val name: String, val age: Int)
In your test, you can indicate how elements can be paired using the pairingMismatchesBy method:
val users: List<User> = ...
assertThat(users)
.pairingMismatchesBy { it.id }
.containsExactly(expectedUsers)
Output:
A collection did not contain exactly the expected element(s)
Expected exactly all elements from: [ User(id=1, name=Ann, age=30), User(id=2, name=Bob, age=40), User(id=3, name=Chuck, age=26), User(id=4, name=Diana, age=50) ]
But was : [ User(id=1, name=Ann, age=30), User(id=2, name=Bob, age=41), User(id=3, name=Chuck, age=27) ]
Missing : [ User(id=4, name=Diana, age=50) ]
Mismatch : • expected User(id=2, name=Bob, age=40)
but was User(id=2, name=Bob, age=41)
• expected User(id=3, name=Chuck, age=26)
but was User(id=3, name=Chuck, age=27)
Thanks to mismatches, it’s now easy to see at a glance that only Diana was truly missing. Bob and Chuck were in both
lists, just with different values. Without mismatches, you would get “Missing: Bob(40), Chuck(26), Diana(50)” and
“Extraneous: Bob(41), Chuck(27)”, which is visually harder to parse.
Maps support mismatches automatically, pairing their entries by key.
The “unused return value” checker
Starting in Kotlin 2.3.0, you can enable warnings for ignored return values.
Truthish supports this feature as of version 2.0.0.
For example, below, the user should have written assertThat(myMap).isEmpty() but instead autocompleted the isEmpty
call in the wrong place, resulting in no-op code. With this feature enabled, they will get a useful warning:
assertThat(myMap.isEmpty())
// ~~~~~~~~~~
// Unused return value of 'assertThat'
Starting in Kotlin 2.5.0, the checker is stable and on by default, so there’s nothing to set up. In Kotlin 2.3 and 2.4,
it’s experimental, so you need to opt into it in your module’s build script:
// build.gradle.kts
// Only needed for Kotlin 2.3 and 2.4
kotlin {
compilerOptions {
freeCompilerArgs.add("-Xreturn-value-checker=check")
}
}
Using Truthish in Your Project
To use Truthish in your multiplatform application, declare any of the following dependencies relevant to your project:
// build.gradle.kts
// Multiplatform
repositories {
mavenCentral()
}
kotlin {
jvm()
js {
browser()
nodejs()
}
wasmJs {
browser()
nodejs()
d8()
}
linuxArm64()
linuxX64()
macosArm64() // Apple Silicon Macs
mingwX64() // Windows
iosArm64() // iOS devices
iosX64() // iOS simulator on Intel Macs
iosSimulatorArm64() // iOS simulator on Apple Silicon Macs
android() // For KMP Android library; may be `androidTarget` for older projects
sourceSets {
commonTest.dependencies {
implementation("com.varabyte.truthish:truthish:2.0.0")
implementation(kotlin("test"))
}
}
}
You can also use Truthish in non-multiplatform projects as well:
JVM
// build.gradle.kts
repositories {
mavenCentral()
}
dependencies {
// ...
testImplementation(kotlin("test"))
testImplementation("com.varabyte.truthish:truthish:2.0.0")
}
Android
// build.gradle.kts
repositories {
mavenCentral()
}
android { /* ... */ }
dependencies {
// ...
// If used in tests that are run on the host (i.e. your dev machine)
testImplementation("com.varabyte.truthish:truthish:2.0.0")
// If used in tests that are run on the device
androidTestImplementation("com.varabyte.truthish:truthish:2.0.0")
}
Testing snapshots
Most users won’t ever need to run a Truthish snapshot, so feel free to skip this section! However, occasionally, bug
fixes and new features will be available for testing for a short period before they are released.
If you ever file a bug with Truthish and are asked to test a fix using a snapshot, you must add an entry for the sonatype
snapshots repository to your repositories block in order to allow Gradle to find it:
// build.gradle.kts
repositories {
mavenCentral()
+ maven("https://central.sonatype.com/repository/maven-snapshots/") {
+ mavenContent {
+ includeGroup("com.varabyte.truthish")
+ snapshotsOnly()
+ }
+ }
}
评论