SetUp and TearDown in Test module?

@jzr offers a good suggestion, so let’s expand to make it more explicit. The do-notation does make setup and teardown pretty. If you want to isolate tests, the SafeTestsets.jl package defines a different macro for the unit test, to create an automatic module for it. This can make it hard to load a package macro in the test, but it usually works fine. It does mean you have to define helper functions inside a module so that they can be loaded. It’s not difficult in practice and looks like this.

module TestHelpers
  function setupteardown(f)
    resources = ...setup...
    try
      f(resources)
    finally
      ...teardown...
    end
  end
end
@safetestset "this invariant is true" begin
  using ..TestHelpers
  setupteardown() do resources
    @test any(resources)
  end
end

You can put your setup and teardown helpers into another file, as long as you include it before the tests in the runtests.jl file.

4 Likes