Unit tests are declared in the test/runtests.jl
file in a package. Typically, this file begins
using MyModule
using Base.Test
The basic unit of testing is the @test
macro. This macro is like an assertion of sorts. Any boolean expression can be tested in the @test
macro:
@test 1 + 1 == 2
@test iseven(10)
@test 9 < 10 || 10 < 9
We can try out the @test
macro in the REPL:
julia> using Base.Test
julia> @test 1 + 1 == 2
Test Passed
Expression: 1 + 1 == 2
Evaluated: 2 == 2
julia> @test 1 + 1 == 3
Test Failed
Expression: 1 + 1 == 3
Evaluated: 2 == 3
ERROR: There was an error during testing
in record(::Base.Test.FallbackTestSet, ::Base.Test.Fail) at ./test.jl:397
in do_test(::Base.Test.Returned, ::Expr) at ./test.jl:281
The test macro can be used in just about anywhere, such as in loops or functions:
# For positive integers, a number's square is at least as large as the number
for i in 1:10
@test i^2 ≥ i
end
# Test that no two of a, b, or c share a prime factor
function check_pairwise_coprime(a, b, c)
@test gcd(a, b) == 1
@test gcd(a, c) == 1
@test gcd(b, c) == 1
end
check_pairwise_coprime(10, 23, 119)