写一个简单的测试

单元测试在包中的 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)