🎓 A1Learner
🔍
0 of 47 lessons completed

Julia Writing Tests

Writing tests is code that checks other code with small named checks. Each check states one expected value, and the group reports how many passed.

A testset groups small checks

The group is named addition and holds two checks. Its summary is hidden, and the printed pass count is 2.

using Test
ts = redirect_stdout(devnull) do
    @testset "addition" begin
        @test 1 + 1 == 2
        @test 2 + 2 == 4
    end
end
println(ts.n_passed)

Checks can test a function

The double function is checked with three values. Its summary is hidden, and the printed pass count is 3.

using Test
function double(x)
    return 2 * x
end
ts = redirect_stdout(devnull) do
    @testset "double" begin
        @test double(21) == 42
        @test double(0) == 0
        @test double(-3) == -6
    end
end
println(ts.n_passed)

Checks can test a refused value

The bad function always throws an ArgumentError. The check expects that error, and the printed pass count is 1.

using Test
function bad()
    throw(ArgumentError("x"))
end
ts = redirect_stdout(devnull) do
    @testset "errors" begin
        @test_throws ArgumentError bad()
    end
end
println(ts.n_passed)

Example

using Test
function shout(word)
    return uppercase(word)
end
ts = redirect_stdout(devnull) do
    @testset "shout" begin
        @test shout("hi") == "HI"
        @test shout("yo") == "YO"
    end
end
println(ts.n_passed)

Key points

  • Test: a check that states one expected value.
  • Testset: a named group of checks run together.
  • Using Test: the line that loads the Test tools before any check runs.
  • Pass: a check whose expected value matches the real value.
  • Total: the count of all checks in the group.
  • Pass count: the testset value n_passed holds the number of checks that passed.

In this example, shout turns words to upper case, and the testset checks hi and yo. The summary is hidden, and the printed pass count is 2.

Note

the summary is hidden while the checks run, since its time changes from run to run.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

A testset holds 3 checks. All 3 pass. What does println(ts.n_passed) print?