寫一個簡單的測試
單元測試在包中的 test/runtests.jl
檔案中宣告。通常,此檔案開始
using MyModule
using Base.Test
測試的基本單位是 @test
巨集。這個巨集就像一個斷言。可以在 @test
巨集中測試任何布林表示式:
@test 1 + 1 == 2
@test iseven(10)
@test 9 < 10 || 10 < 9
我們可以在 REPL 中試用 @test
巨集:
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
測試巨集幾乎可以在任何地方使用,例如迴圈或函式:
# 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)