Repository navigation
v2.0.0
Using Truthish 2.0.0 in your tests should look exactly the same as any 1.x release, but under the hood, we completely refactored the APIs from an inheritance class system to an extension function system.
If you update your project's truthish dependency, hopefully nothing needs to change except the addition of:
import com.varabyte.truthish.assertions.*at the top of your tests.
In addition to this change, this new version lands with a ton of new assertions, and support for features called Correspondences (for looser collection matching) and Mismatches (for clearer reports when related items differ). These (and more) are discussed below.
Kotlin versions
Requirements are now:
- Kotlin 2.3+ for JVM projects
- Kotlin 2.5+ for JS, Wasm, and Native projects
Before, Truthish aimed to support as wide a userbase as possible, but this required staying on very old versions of Kotlin.
We have since realized this was costing us useful API updates and language features, and when we looked at state-of-the-art libraries in the ecosystem, we saw that no one else was doing this (including official Kotlin libraries). So, we started following a new policy -- use the latest compiler available to us and support back to as many versions as that allows.
Breaking changes
-
Assertions are now extension functions, in the
com.varabyte.truthish.assertionspackage.- Add a second wildcard import to your tests:
import com.varabyte.truthish.* import com.varabyte.truthish.assertions.*
- This new approach lets assertions check their argument types at compile time, so now many invalid comparisons simply refuse to compile instead of failing at runtime.
- The one valid case that may now fail to compile is comparing a subtype against a supertype. To fix such a test, you can either add an explicit type:
assertThat<Animal>(dog).isEqualTo(animal)or else reverse the assertion order:assertThat(animal).isEqualTo(dog)- In our experience, this case is exceptionally rare.
- Add a second wildcard import to your tests:
-
APIs around Sequences, Arrays and Maps have been made stricter:
assertThat(sequence).isEqualTo(...)only takes another sequence.- To compare with a list, use
containsExactly(list).inOrder().
- To compare with a list, use
- A primitive array can no longer be compared with a boxed one (e.g.
IntArraywithArray<Int>). - Maps lose checks that never made sense for them, like
hasNoDuplicates().
-
Some assertions are stricter:
containsAnyIn()with nothing to look for now fails instead of passing. Passing used to hide tests whose expected list was accidentally empty. (This was a mistake before. Now, this behavior matches Kotlin'sany {}.)containsAllIn()now counts duplicates, soassertThat(listOf(1)).containsAllIn(1, 1)fails, reporting the
missing1.
-
The
macosX64target is gone. Kotlin is deprecating it, since Apple has moved off Intel Macs.
Deprecations
isGreaterThanEqual()andisLessThanEqual()are renamed toisAtLeast()andisAtMost().- This is what Truth uses, and, honestly, the new names read better and are less verbose.
New features
IDE diffs
If you are running tests inside IntelliJ IDEA and using JUnit 4+ as your test runner, you should start seeing a "Click to see difference" link, which opens up a very helpful view in the IDE's diff viewer.
Much better failure reports
- Line diffs for multi-line strings:
Diff: a - B + b c - Missing and extraneous elements are listed when collections or maps aren't equal.
- Long values are truncated around what went wrong, e.g. a 10,000-element list is centered on the element that failed, and long strings on their first difference.
- If there are multiple failures, Truthish just focuses on the first.
inOrder()now shows where the order broke.hasSize(),hasLength()andisNotBlank()show the value that failed, not just its size or length.- More readable values:
- simple class names instead of
class java.lang.Integer (Kotlin reflection is not available) { "a" to 1 }instead of{ a=1 }[]for empty collections,<anonymous>for anonymous classes- escaped control characters (e.g.
"a\tb").
- simple class names instead of
New assertions
hasMessageThat()andhasCauseThat()for throwablesisInOrder(), to check that a collection is sortedisIn()andisNotIn(), for rangesisAnyOf()andisNoneOf(), on every subjectisNaN(),isFinite(),isZero()and friends for floats and doublescontainsEntry()anddoesNotContainEntry()for mapsignoreCaseforisEqualTo(),contains(),startsWith(),endsWith()and friends on stringsinOrder(consecutive = true)aftercontainsAllIn(), to check for an unbroken run of elements
Correspondences
Sometimes you want to compare two collections more loosely than exact equality.
For example, say you have a list of error Strings which you generate that are very long. Their text may change over time, but the strings will always contain a general category of the error (e.g. the "Unresolved reference" part of "/very/long/path/to/file.kt[123]: Unresolved reference -- The value xyz could not be resolved; please check your imports.")
Instead of writing
assertThat(errors)
.containsExactly(
"/very/long/path/to/File.kt[123]: Unresolved reference -- The value xyz could not be resolved; please check your imports.",
"/very/long/path/to/another/DifferentFile.kt[92]: Type mismatch -- Variable is type Cat but expected type Dog"
)you can use a correspondence:
assertThat(errors)
.comparingElementsUsing(Correspondence.contains)
.containsExactly("Unresolved reference", "Type mismatch")- For maps, use
comparingValuesUsing.
Mismatches
When a collection check fails, and if there's some clear way to identify related elements based on some common value, then you can tell Truthish how expected and actual elements can pair up. Paired elements move out of the Missing and Extraneous rows into a Mismatch row, which can make the change much easier to see at a glance, especially in a test failure resulting in multiple differences.
data class User(val id: Int, val name: String, val age: Int)
assertThat(users)
.pairingMismatchesBy { it.id }
.containsExactly(expectedUsers)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=27)
but was User(id=3, name=Chuck, age=25)
Above, we can tell at a glance that both actual and expected collections had a "Bob" and a "Chuck", while only expected had a "Diana". Without mismatches, you would have roughly gotten "Missing: Bob, Chuck, Diana; Extraneous: Bob, Chuck".
If you are comparing two maps to each other, elements will automatically be paired by key for you.
If you need to add additional information to the mismatch rows, you can explain them (where returning null means you have nothing to say):
.pairingMismatchesBy { it.id }
.explainingMismatchesWith { actual, expected ->
if (actual.age != expected.age) "age is off by ${abs(actual.age - expected.age)}" else null
}
.containsExactly(expectedUsers)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)
→ age is off by 1
• expected User(id=3, name=Chuck, age=27)
but was User(id=3, name=Chuck, age=25)
→ age is off by 2
- You can use
pairingMismatchesWhen { actual, expected -> ... }if you need more flexibility thanpairingMismatchesBy. - Coming from Truth? The equivalents there are
displayingDiffsPairedByandformattingDiffsUsing. - The feature works with correspondences too.
Unused return value warnings
Truthish supports Kotlin's unused return value checker.
It can be very easy to write an unfinished assertion chain unintentionally! For example:
// assertThat(map).isEmpty() // <- Meant to write this...
assertThat(map.isEmpty()) // <- but wrote this...Before, that line silently did nothing, potentially allowing a test to pass when it should have failed. Now, the compiler and IDE will highlight a warning: Unused return value of 'assertThat'
The checker is on by default starting in Kotlin 2.5. In Kotlin 2.3 and 2.4, opt in with -Xreturn-value-checker=check (see the README).
Custom subjects
In 1.x, custom subjects couldn't do everything the built-in ones could. 2.0.0 fixes that.
This will be much clearer with a concrete example. Let's imagine your popular library has a User class, and you want to support Truthish users by letting them test against it with its own subject type.
To do this:
- Create a subclass of
Subject<T>, whereTis your class. - Define a
thatextension function (receivingAssertionEntryPoint) which just callsprepareon your subject. - Define an
assertThatfunction which delegates tothat.
Bringing it all together:
class UserSubject(private val user: User) : Subject<User>(user) {
fun hasName(name: String) = Subject(user.name).derivedFrom(this).valueOf("User.name").isEqualTo(name)
}
fun AssertionEntryPoint.that(user: User) = prepare(UserSubject(user))
fun assertThat(user: User) = AssertionEntryPoint.that(user)At this point, you can pass a user instance into assertThat(user), assertWithMessage("...").that(user), and assertAll { that(user) }.
Subjects for collection-like types (e.g. a multimap) can extend ElementsSubject or KeyedSubject instead, and get the built-in collection checks for free, including mismatches and correspondences.
Documentation
Every public API is now documented, so your IDE's quick documentation works everywhere.
Fixes
isWithinreported expected and actual values swapped, and didn't catchNaN.assertThrowsdidn't properly handle the case if a different exception than what it was expecting was thrown.- The unexpected exception is now kept as the cause, so its stack trace isn't lost.
- In
assertAllreports, the "At" entry now points at the right line, even for custom subjects (before, this only worked for assertions defined inside Truthish itself).
Full Changelog: v1.0.4...v2.0.0