Skip to content

v2.0.1

Latest

Choose a tag to compare

@bitspittle bitspittle released this 04 Dec 20:57

Note

2.0.1 is 2.0.0 with a bit of API cleanup.

A handful of minor modifier extension functions moved from their old 1.0.4 location to a new package for a clearer
import experience. The old imports still work but are deprecated.

We also made a few properties on the Reportable class internal. They could have cluttered autocomplete while you were
building an assertion chain, and there should never be a reason to use them directly. We meant to clean up all cases
like this in 2.0.0 but missed a spot. Technically this is a backwards incompatible change, so if it causes you any
trouble, please file an issue!

The rest of these release notes are copied from 2.0.0 as is.

Using Truthish 2.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.assertions package.

    • 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.
  • 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().
    • A primitive array can no longer be compared with a boxed one (e.g. IntArray with Array<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's any {}.)
    • containsAllIn() now counts duplicates, so assertThat(listOf(1)).containsAllIn(1, 1) fails, reporting the
      missing 1.
  • The macosX64 target is gone. Kotlin is deprecating it, since Apple has moved off Intel Macs.

Deprecations

  • isGreaterThanEqual() and isLessThanEqual() are renamed to isAtLeast() and isAtMost().
    • 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.

show-diff-link
diff-view

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() and isNotBlank() 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").

New assertions

  • hasMessageThat() and hasCauseThat() for throwables
  • isInOrder(), to check that a collection is sorted
  • isIn() and isNotIn(), for ranges
  • isAnyOf() and isNoneOf(), on every subject
  • isNaN(), isFinite(), isZero() and friends for floats and doubles
  • containsEntry() and doesNotContainEntry() for maps
  • ignoreCase for isEqualTo(), contains(), startsWith(), endsWith() and friends on strings
  • inOrder(consecutive = true) after containsAllIn(), 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 than pairingMismatchesBy.
  • Coming from Truth? The equivalents there are displayingDiffsPairedBy and formattingDiffsUsing.
  • 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 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>, where T is your class.
  • Define a that extension function (receiving AssertionEntryPoint) which just calls prepare on your subject.
  • Define an assertThat function which delegates to that.

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

  • isWithin reported expected and actual values swapped, and didn't catch NaN.
  • assertThrows didn'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 assertAll reports, 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.1