# SetUp and TearDown in Test module?

**URL:** <https://discourse.julialang.org/t/setup-and-teardown-in-test-module/68589>\
**Category:** General Usage\
**Tags:** question, testing, testjl-unittesting\
**Created:** [September 22, 2021, 3:29pm UTC](https://discourse.julialang.org/t/setup-and-teardown-in-test-module/68589 "2021-09-22T15:29:20Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![adolgert](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/adolgert/32/20286_2.png) [@adolgert](https://discourse.julialang.org/u/adolgert)\
**Post date:** [September 23, 2021, 1:40am UTC](https://discourse.julialang.org/t/setup-and-teardown-in-test-module/68589/4 "2021-09-23T01:40:41Z")

</div>

@jzr offers a good suggestion, so let’s expand to make it more explicit. The [do-notation](https://docs.julialang.org/en/v1/manual/functions/#Do-Block-Syntax-for-Function-Arguments) does make setup and teardown pretty. If you want to isolate tests, the [SafeTestsets.jl](https://github.com/YingboMa/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.

```julia
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.

---

_[View the full topic](https://discourse.julialang.org/t/setup-and-teardown-in-test-module/68589)._
