← Back to lesson 25: Test behavior and boundaries

Test behavior and boundaries: full examples and further reading

The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.

Use setup data, doctests, focused assertions, and async-safe tests.

Write one normal assertion and one boundary assertion for the same pure function.

Run this first

Run it once, change one input, and compare the new result.

Original full example
# lib/score.ex
defmodule Score do
  def pass?(score) when is_integer(score) and score in 60..100, do: true
  def pass?(_score), do: false

  def check(score) when is_integer(score) and score in 0..100,
    do: {:ok, score}

  def check(_score), do: {:error, :out_of_range}
end

# test/score_test.exs
defmodule ScoreTest do
  use ExUnit.Case, async: true

  test "pass boundary" do
    assert Score.pass?(60)
    refute Score.pass?(59)
  end
end

mix test reports one passing test containing two boundary assertions.

Steps for the full example

  1. Read use ExUnit.Case, async: true: Allow independent tests to run concurrently.
  2. Read setup: Return context data for each test.
  3. Read doctest Module: Run documented IEx examples as tests.

Original lesson notes

Run the example first. Predict one result, then change one input and run it again.

Boundary cases sit where behavior changes, such as 59 versus 60.

A setup callback prepares fresh data for each test.

Symbols and terms
use ExUnit.Case, async: true
Allow independent tests to run concurrently.
setup
Return context data for each test.
doctest Module
Run documented IEx examples as tests.
test boundary
Boundary cases sit where behavior changes, such as 59 versus 60.
setup
A setup callback prepares fresh data for each test.
doctest
Doctest runs examples written in module documentation.

Original full exercise

Add a test that rejects a negative score.

Exercise starter
test "negative score" do
  assert Score.check(-1) == ____
end

Expect {:error, :out_of_range}.

Show hint

Use the tagged error returned by the public API.

Show original answer
Reference answer
test "negative score" do
  assert Score.check(-1) == {:error, :out_of_range}
end
When is async: true unsafe?

Avoid it when tests share mutable external state such as one database record or global process.

Original lesson takeaways
Design trade-offs and language comparisons
Original course references