Writing Tests
Last updated on 2026-01-27 | Edit this page
Overview
Questions
How can I make my programs more reliable?
Objectives
- Explain what a test is.
- Explain what an assertion is.
- Use tests and assertions to check my code.
Why Testing Matters
When we write code, we want to be confident that it produces the
right results.
Additionally, it should keep working when we make changes. And even if
we make mistakes,
they should be caught early.
Julia provides two simple ways to test your code:
-
@test(from theTeststandard library). -
@assert(built-in macro).
Using @test
The @test macro is part of Julia’s Test
standard library.
It checks whether an expression evaluates to true.
If not, the test fails but your program keeps running.
OUTPUT
Test Passed
OUTPUT
Test Passed
OUTPUT
Test Passed
OUTPUT
Test Failed at REPL[5]:1
Expression: 10 / 3 == 3
Evaluated: 3.3333333333333335 == 3
ERROR: There was an error during testing
@test reports failures without stopping execution. You
usually use it for larger projects where you want to test many things at
once. For these cases, there is another structure we can use:
@testset.
OUTPUT
Test Summary: | Pass Total Time
Math tests | 3 3 0.1s
Test.DefaultTestSet("Math tests", Any[], 3, false, false, true, 1.75629781203e9, 1.756297812095e9, false)
The @assert Macro
The @assert macro is built into Julia. It also checks if
an expression is true, but if the check fails, it
immediately throws an error and stops the program.
OUTPUT
ERROR: AssertionError: 10 / 3 == 3
Stacktrace:
[1] top-level scope
@ REPL[8]:1
You can also provide a custom error message:
OUTPUT
ERROR: AssertionError: x must be non-negative!
Stacktrace:
[1] top-level scope
@ REPL[10]:1
When to Use What?
- Use
@testwhen writing test files or checking lots of conditions at once. - Use
@assertinside your program to enforce assumptions (like “input must be positive”).
Test
Write a function
is_even(n)that returnstrueifnis even.-
Add a testset that checks:
-
is_even(2)istrue. -
is_even(3)isfalse.
-
Add an assertion in your function that throws an error if
nis not an integer.