---
url: https://wvlet.org/uni/unitest.md
description: >-
  Learn UniTest in one page. Set up the Scala 3 testing framework, then write
  assertions, fixtures, async tests, property tests, and fuzz tests, on the JVM,
  Scala.js, and Scala Native.
---

# UniTest Quick Start

UniTest is a testing framework for Scala 3. One dependency covers everyday
assertions, test fixtures, async tests, property-based testing, and fuzz testing,
and the same tests run on the JVM, Scala.js, and Scala Native.

```scala
import wvlet.uni.test.*

class HelloTest extends UniTest:
  test("addition works") {
    1 + 1 shouldBe 2
  }
```

* **Small to learn:** extend `UniTest`, write `test("name") { ... }`, and compare with `shouldBe`.
* **Nothing else to add:** generators, shrinking, and a fuzzer are built in.
* **Only in your tests:** add `uni-test` in the `Test` scope. Your main code does not need Uni.
* **Easy to try:** sbt runs several test frameworks in one project, so you can add UniTest suites
  next to the tests you already have.

This page sets up UniTest, lists [assertions](#assertion-cheat-sheet) and
[sbt commands](#sbt-cheat-sheet) you can come back to, and walks through testing one small program.

## 1. Set up

Add UniTest to an sbt project that uses Scala 3 and JDK 25 or later (Uni targets the
[latest LTS release](../guide/principles#latest-lts-jdk)):

```scala sbt
// build.sbt
scalaVersion := "3.9.0"

resolvers += "wvlet" at "https://repo.wvlet.org/maven2"
libraryDependencies += "org.wvlet.uni" %% "uni-test" % "2026.4.1" % Test
testFrameworks += new TestFramework("wvlet.uni.test.Framework")
```

For Scala.js and Scala Native on sbt 1.x, use `%%%` (see
[Installation](../guide/installation#cross-platform-projects)).

## Assertion cheat sheet

`import wvlet.uni.test.*` and extend `UniTest` to use all of these:

| Syntax | Meaning |
|:-------|:--------|
| `assert(x == y)` | Check x equals y |
| `assertEquals(a, b, delta)` | Check Float/Double equality with tolerance |
| `intercept[E] { ... }` | Catch an exception of type E |
| `x shouldBe y` | Check x == y (supports deep equality for Array, Seq) |
| `x shouldNotBe y` | Check x != y |
| `x shouldBe null` | Check x is null |
| `x shouldNotBe null` | Check x is not null |
| `x shouldBe defined` | Check x.isDefined == true (Option, Seq, String) |
| `x shouldBe empty` | Check x.isEmpty == true (Option, Seq, String) |
| `x shouldBeTheSameInstanceAs y` | Check x eq y (reference equality) |
| `x shouldNotBeTheSameInstanceAs y` | Check x ne y (reference inequality) |
| `x shouldMatch { case .. => }` | Check x matches the pattern, then run the assertions in the case |
| `x shouldContain y` | Check x contains y |
| `x shouldNotContain y` | Check x does not contain y |
| `x shouldBeInAnyOrder y` | Check the same elements in any order ([Comparing Results](./results)) |
| `fail("reason")` | Fail the test |
| `ignore("reason")` | Ignore the test |
| `cancel("reason")` | Cancel the test (e.g., setup failure) |
| `pending("reason")` | Mark test as pending |
| `pendingUntil("reason")` | Pending until condition is fixed |
| `skip("reason")` | Skip the test (e.g., platform-specific) |
| `flaky { ... }` | Report a failure in the block as skipped |

For comparisons, use `(x > 5) shouldBe true`. Examples: [Assertions](./assertions),
[Test Control](./organizing#test-control)

## sbt cheat sheet

Run these from your shell, or start `sbt` once and type the part in quotes at its prompt:

| Command | What it runs |
|:--------|:-------------|
| `sbt test` | All tests (on sbt 2, only those affected by changes) |
| `sbt testFull` | All tests again, changed or not (sbt 2) |
| `sbt "testOnly *CodeTest"` | Suites whose full name ends with `CodeTest` |
| `sbt "testOnly com.example.*"` | All suites in a package |
| `sbt "testOnly *CodeTest *LinkServiceTest"` | Several suites |
| `sbt "testOnly * -- encode"` | Tests whose name contains `encode` |
| `sbt "testOnly *CodeTest -- enc*ID"` | Tests of one suite, where `*` stands for any text |
| `sbt 'testOnly * -- "encode an ID"'` | Tests whose name contains the words, quoted for the spaces |
| `sbt "testOnly * -- outer/inner"` | Nested tests matching `inner`, inside tests matching `outer` |
| `sbt "testOnly *CodeTest -- -l debug"` | One suite, showing debug logs |
| `sbt "testOnly * -- -l:com.example.*=trace"` | All suites, showing trace logs of one package |
| `sbt "testOnly * -- --tags slow"` | Tests tagged `slow` |
| `sbt "testOnly * -- --exclude-tags slow"` | All tests except those tagged `slow` |
| `sbt "~testOnly *CodeTest"` | One suite, again after every source change |

UniTest options go after `--` and can be combined, as in
`testOnly *CodeTest -- encode -l debug`. More: [Running Tests](./running)

## 2. The program to test

A link shortener stores URLs and gives each one a short code. It is plain Scala.
Save it as `src/main/scala/Links.scala`:

```scala
object Code:
  private val digits = ('0' to '9') ++ ('a' to 'z')

  // 35 -> "z", 36 -> "10"
  def encode(id: Int): String =
    val sb = StringBuilder()
    var n  = id
    while n > 0 do
      sb.append(digits(n % 36))
      n /= 36
    sb.reverse.toString

  def decode(code: String): Int = Integer.parseInt(code, 36)

trait LinkStore:
  def add(url: String): String
  def find(code: String): Option[String]

class InMemoryLinkStore extends LinkStore:
  private var urls = Vector.empty[String]

  def add(url: String): String =
    urls = urls :+ url
    Code.encode(urls.size)

  def find(code: String): Option[String] = urls.lift(Code.decode(code) - 1)

class LinkService(store: LinkStore):
  def shorten(url: String): String         = store.add(url)
  def resolve(code: String): Option[String] = store.find(code)
```

## 3. Write your first tests

Save this as `src/test/scala/CodeTest.scala`:

```scala
import wvlet.uni.test.*

class CodeTest extends UniTest:
  test("encode an ID") {
    Code.encode(35) shouldBe "z"
    Code.encode(36) shouldBe "10"
  }

  test("reject an invalid code") {
    val e = intercept[NumberFormatException] {
      Code.decode("?")
    }
    e.getMessage shouldContain "?"
  }

  test("find a stored link") {
    val store = InMemoryLinkStore()
    val code  = store.add("https://example.org")

    store.find(code) shouldBe defined
    store.find(code) shouldMatch { case Some(url) =>
      url shouldBe "https://example.org"
    }
    store.find("zz") shouldBe empty
  }
```

Run the tests with `sbt test`:

```text
CodeTest:
  + encode an ID (10ms)
  + reject an invalid code (0ms)
  + find a stored link (0ms)
  3 tests, 3 passed (22ms)
```

A failed assertion shows both values and the line. With `"Z"` instead of `"z"`:

```text
  - encode an ID: Expected <Z> but got <z> (CodeTest.scala:5) (10ms)
    5|     Code.encode(35) shouldBe "Z"
                                      ^
```

More: [Assertions](./assertions), [Organizing Tests](./organizing)

## 4. Share setup with fixtures

`LinkService` needs a `LinkStore`. Instead of building them in every test, say
which implementation to use, and take what you need as test arguments:

```scala
import wvlet.uni.test.*

class LinkServiceTest extends UniTest:
  addTestDesign(_.bindImpl[LinkStore, InMemoryLinkStore])

  test("resolve a shortened link") { (service: LinkService) =>
    val code = service.shorten("https://example.org")
    service.resolve(code) shouldBe Some("https://example.org")
  }

  test("start with an empty store") { (service: LinkService) =>
    service.resolve("1") shouldBe None
  }
```

UniTest builds the arguments from their constructors. `addTestDesign` gives each
test its own objects, so one test cannot affect another. [Step 6](#_5-open-and-close-resources)
shows how to share objects across tests and close them.

More: [Fixtures & Lifecycle](./fixtures)

## 5. Open and close resources

Many tests need something that has to be opened before and closed after: a database,
a server, a temp directory. Forgetting to close it leaks ports and files into the next
test, above all when a test fails halfway.

With UniTest you don't write that cleanup in each test. Make the resource a class that
extends `AutoCloseable`, acquire it in the constructor, and release it in `close()`.
Then bind it in the suite's **Design**, a description of how to build the objects your
tests need, and take it as a test argument:

```scala
import wvlet.uni.log.LogSupport
import wvlet.uni.test.*

// Slow to start, so the whole suite shares one
class TestDatabase extends LogSupport with AutoCloseable:
  info("start database")
  override def close(): Unit = info("stop database")

// Cheap to open, so each test gets its own
class Connection(db: TestDatabase) extends LogSupport with AutoCloseable:
  info("open connection")
  def query(sql: String): Int = 1
  override def close(): Unit = info("close connection")

class DatabaseTest extends UniTest:
  addDesign(_.bindSingleton[TestDatabase])   // shared by the tests of this suite
  addTestDesign(_.bindSingleton[Connection]) // new for each test

  test("query") { (conn: Connection) =>
    conn.query("select 1") shouldBe 1
  }

  test("another query") { (conn: Connection) =>
    conn.query("select 2") shouldBe 1
  }
```

`Connection` needs a `TestDatabase`, and UniTest passes it the shared one. `info`
comes from `LogSupport`, Uni's logger, and shows the source line of each message. The
output, with timestamps removed and columns aligned, shows when each resource is opened and closed:

```text
info [TestDatabase] start database    - (DatabaseTest.scala:6)
info [Connection]   open connection   - (DatabaseTest.scala:11)
info [Connection]   close connection  - (DatabaseTest.scala:13)
info [Connection]   open connection   - (DatabaseTest.scala:11)
info [Connection]   close connection  - (DatabaseTest.scala:13)
info [TestDatabase] stop database     - (DatabaseTest.scala:7)
```

| Bind with | Created | Closed | Use for |
|-----------|---------|--------|---------|
| `addDesign` | Once, when a test first needs it | After the last test of the suite | Slow resources: servers, databases |
| `addTestDesign` | For each test that needs it | After that test | Cheap or changeable state: connections, temp directories |

* **Failing tests:** resources are closed when a test fails, too.
* **Order:** resources close in reverse order of creation, so a connection closes before its database.
* **Only when needed:** a resource that no test asks for is never opened.

For a class that is not `AutoCloseable`, say how to release it:

```scala
class EmbeddedServer extends LogSupport:
  def stop(): Unit = info("stop server")

class ServerTest extends UniTest:
  addDesign(_.bindSingleton[EmbeddedServer].onShutdown(_.stop()))

  test("use the server") { (server: EmbeddedServer) =>
    server shouldNotBe null
  }
```

More: [Reusable Fixtures](./fixtures#reusable-fixtures), to share resources across suites

## 6. Test async code

Some code finishes later than the call that starts it: an HTTP request, a database
query, or work on another thread. Testing it is tricky, because a test body can reach
its end before the result arrives, and an assertion that runs after that is too late
to fail the test.

Uni represents such work as an **`Rx`**: a description of a value, or a stream of
values, that arrives later. Use `map` to say what to do with the value. Nothing runs
until someone subscribes to the `Rx`, and in a test, that someone is UniTest. So the rule is
simple: **make the `Rx` the last expression of the test**. UniTest runs it, waits for
its first value, and reports the result, with no blocking or `sleep`.

Let's test a real HTTP client. Uni's HTTP client and server are in `uni`, so this step
needs one more test dependency:

```scala sbt
libraryDependencies += "org.wvlet.uni" %% "uni" % "2026.4.1" % Test
```

The test starts its own server on a free port, so it needs no network and cannot fail
because some other site is down. The server is a resource like the database in step 5,
and the client is built from it:

```scala
import wvlet.uni.http.{Http, HttpAsyncClient, HttpException, Request, Response}
import wvlet.uni.log.LogSupport
import wvlet.uni.test.*

class TestServer extends LogSupport with AutoCloseable:
  private val server = Http
    .server
    .withPort(0) // use any free port
    .withHandler { request =>
      if request.path.startsWith("/hello/") then
        Response.ok(s"Hello, ${request.path.stripPrefix("/hello/")}!")
      else
        Response.notFound
    }
    .start()

  def uri: String = s"http://localhost:${server.localPort}"

  override def close(): Unit =
    server.close()
    info("stop server")

class HttpClientTest extends UniTest:
  addDesign(
    _.bindSingleton[TestServer]
      .bindProvider[TestServer, HttpAsyncClient](server =>
        Http.client.withBaseUri(server.uri).newAsyncClient
      )
  )

  test("send a request") { (client: HttpAsyncClient) =>
    client.send(Request.get("/hello/Ann")).map { response =>
      response.contentAsString shouldBe Some("Hello, Ann!")
    }
  }

  test("send two requests, one after the other") { (client: HttpAsyncClient) =>
    for
      ann <- client.send(Request.get("/hello/Ann"))
      bob <- client.send(Request.get("/hello/Bob"))
    yield
      ann.contentAsString shouldBe Some("Hello, Ann!")
      bob.contentAsString shouldBe Some("Hello, Bob!")
  }

  test("expect an error") { (client: HttpAsyncClient) =>
    client
      .send(Request.get("/missing"))
      .map(response => response.status.code)
      .recover { case e: HttpException => e.statusCode.getOrElse(0) }
      .map { status =>
        status shouldBe 404
      }
  }
```

* **The result:** `send` returns an `Rx` of the response, and the assertions go in `map`.
* **Failures:** the test fails if an assertion fails or if the `Rx` itself fails. A 404
  makes `send` fail, so the last test turns the error into a value with `recover`.
* **Cleanup:** the client and the server stay open until the last `Rx` ends, and then close.
* **Platforms:** this example runs on the JVM and Scala Native. On Node.js a server starts
  in the background, so wait for its `whenReady` before using the port.

Always end the test with the `Rx`: one that is left out of the result never runs, so its
assertions are not checked.

Code that uses Scala's `Future` works the same way: return the `Future`, and UniTest
waits for it.

```scala
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import wvlet.uni.test.*

class AsyncLinkTest extends UniTest:
  test("shorten in the background") {
    val service = LinkService(InMemoryLinkStore())
    Future(service.shorten("https://example.org")).map { code =>
      code shouldBe "1"
    }
  }
```

More: [Async Tests](./async), and [Rx Basics](../rx/basics) if `Rx` is new to you

## 7. Property-based testing: check a rule

The tests so far are *example-based*: you choose an input and write the answer you
expect. They only cover the inputs you thought of. In a *property-based* test, you
write a rule that holds for every input, called a **property**, and UniTest makes up
the inputs. Think of it as saying "whatever list you give me, ..." instead of
"for this list, ...".

Here is a function with a bug, and both kinds of test:

```scala
import wvlet.uni.test.*

// Returns the largest number in a list. BUG: wrong for negative numbers (fixed below)
def largest(numbers: List[Int]): Int =
  var result = 0
  for n <- numbers do
    if n > result then
      result = n
  result

class LargestTest extends UniTest:
  // You choose the input and write the expected answer
  test("an example") {
    largest(List(3, 9, 4)) shouldBe 9
  }

  // UniTest chooses the inputs, and you write a rule that always holds
  test("the largest number is in the list") {
    forAll { (numbers: List[Int]) =>
      if numbers.nonEmpty then
        numbers shouldContain largest(numbers)
    }
  }
```

`forAll` runs its body with 100 random lists. The example passes, but the property
fails (lines wrapped here):

```text
  + an example
  - the largest number is in the list:
      Expected <List(-1760582716)> to contain <0>
      (property input: List(-1), seed=976925048672291)
```

Random inputs are hard to read, so UniTest then tries simpler and simpler versions
of the failing input and reports the simplest one that still fails as
`property input`. This is called **shrinking**. `List(-1)` points at the bug:
`result` starts at 0, so a list of negative numbers returns 0. Start from the first
number instead, and the test passes:

```scala skip
  var result = numbers.head
```

You don't need to know the answer to write a property. These rules fit a lot of code:

| Rule | Example |
|------|---------|
| Undoing gives back the original | `decode(encode(x)) shouldBe x` |
| The result is always valid | a sorted list is in order, a price is never negative |
| Doing it twice changes nothing more | `normalize(normalize(s)) shouldBe normalize(s)` |
| A simpler way agrees | `fastSum(xs) shouldBe xs.sum` |

More: [Property-Based Testing](./property)

## 8. Fuzz testing: look for crashes

Some code has to survive input that nobody planned for: text typed by a user, a file,
a network message. **Fuzz testing** throws strange input at such code to see if it
breaks. You give it a valid sample, called a **seed**, and UniTest keeps making random
edits to it (deleting, inserting, and changing characters) and runs your code on each
result. There is no expected answer to write. The test fails when the code throws an
exception, or when an assertion you add fails.

This function reads the port of an address, and should return `None` when there is none:

```scala
import wvlet.uni.test.*

// "localhost:8080" -> Some(8080), and None for text without a port
// BUG: throws when the text after the colon is not a number (fixed below)
def parsePort(address: String): Option[Int] =
  val colon = address.indexOf(':')
  if colon < 0 then None
  else Some(address.substring(colon + 1).toInt)

class ParsePortTest extends UniTest:
  test("read the port") {
    parsePort("localhost:8080") shouldBe Some(8080)
    parsePort("localhost") shouldBe None
  }

  test("never throw on any text") {
    fuzzString("parse-port").withSeeds("localhost:8080") { text =>
      parsePort(text)
    }
  }
```

`"parse-port"` names the fuzz test, `withSeeds` gives it valid samples, and the block is
the code to fuzz. A normal run tries 1,000 edited inputs. This one fails after a few:

```text
  - never throw on any text: Fuzz target parse-port failed on input 4
    with java.lang.NumberFormatException: For input string: ""
  input (1 bytes, reduced from 21): 3a
  as text: ":"
  seed=976828127829125 (replay with UNI_FUZZ_SEED=976828127829125)
  saved to target/fuzz/parse-port/crash-af63b74c8601adad
```

| Line | Meaning |
|------|---------|
| `failed on input 4` | The fourth input made `parsePort` throw `NumberFormatException` |
| `reduced from 21` | The failing input had 21 bytes; UniTest removed everything it could, and one byte was left (`3a`, in hex) |
| `as text: ":"` | The input to look at: an address that ends right after the colon |
| `seed=...` | Set this environment variable to try the same inputs again |
| `saved to ...` | The failing input as a file, which you can keep as a regression test |

The fix is to return `None` when the text after the colon is not a number:

```scala skip
  else address.substring(colon + 1).toIntOption
```

### Which kind of test to use

| | You write | Best for |
|---|-----------|----------|
| Example-based | An input and the expected answer | Specific behavior, and bugs you already fixed |
| Property-based | A rule about every input | Logic over typed values: lists, numbers, case classes |
| Fuzz | A sample input | Parsers and anything that reads outside input |

They work well together. Start with examples, then add a property or a fuzz test
where a surprising input would hurt.

More: [Fuzz Testing](./fuzzing)

## Where to go next

| Page | What it covers |
|------|----------------|
| [Assertions](./assertions) | Examples of every check |
| [Organizing Tests](./organizing) | Nested tests, skip/pending/flaky, platform detection, and tags |
| [Fixtures & Lifecycle](./fixtures) | Test arguments from a Design, hooks, and reusable fixtures |
| [Async Tests](./async) | `Rx` and `Future` test bodies, and subscription leaks |
| [Testing Error Paths](./logs) | `captureLogs`, `captureStdout`, and `captureStderr` |
| [Comparing Results](./results) | Rows in any order, NULL equality, and float tolerance |
| [Property-Based Testing](./property) | `forAll`, generators, and shrinking |
| [Fuzz Testing](./fuzzing) | `fuzz`, `fuzzString`, and `fuzzGen`, with corpus replay and reduction |
| [Running Tests](./running) | sbt commands, test output, and log capture |

To test Scala.js UI components in a real browser, see [DOM Testing](../dom/testing)
and the [sbt-uni-playwright Plugin](../build/sbt-uni-playwright).

## Cross-Platform Support

| Feature | JVM | Scala.js | Scala Native |
|---------|:---:|:--------:|:------------:|
| Basic assertions | ✓ | ✓ | ✓ |
| Nested tests | ✓ | ✓ | ✓ |
| Flaky tests | ✓ | ✓ | ✓ |
| Property-based testing | ✓ | ✓ | ✓ |
| `captureLogs` from other threads | ✓ | - | ✓ |
| IDE integration | ✓ | - | - |
