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.
# 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
endmix test reports one passing test containing two boundary assertions.
Steps for the full example
- Read
use ExUnit.Case, async: true: Allow independent tests to run concurrently. - Read
setup: Return context data for each test. - 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.
test "negative score" do
assert Score.check(-1) == ____
endExpect {:error, :out_of_range}.
Show hint
Use the tagged error returned by the public API.
Show original answer
test "negative score" do
assert Score.check(-1) == {:error, :out_of_range}
endWhen is async: true unsafe?
Avoid it when tests share mutable external state such as one database record or global process.
Original lesson takeaways
- Test behavior, not private steps.
- Place tests on both sides of boundaries.
- Share examples through setup or doctests only when they stay clear.