# Testing error thrown by a macro

**URL:** <https://discourse.julialang.org/t/testing-error-thrown-by-a-macro/116983>\
**Category:** General Usage\
**Tags:** question, testing, macros\
**Created:** [July 12, 2024, 9:36pm UTC](https://discourse.julialang.org/t/testing-error-thrown-by-a-macro/116983 "2024-07-12T21:36:56Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![CameronBieganek](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cameronbieganek/32/6915_2.png) [@CameronBieganek](https://discourse.julialang.org/u/CameronBieganek)\
**Post date:** [July 12, 2024, 9:36pm UTC](https://discourse.julialang.org/t/testing-error-thrown-by-a-macro/116983/1 "2024-07-12T21:36:56Z")

</div>

Is there a standard way to test that a macro throws an error for certain inputs? Consider the following example:

```julia
macro foo(x)
    x == :a || throw(ArgumentError("oops."))
    1
end

```

If I use `@test_throws` normally, it doesn’t catch the error:

```julia-repl
julia> @test_throws ArgumentError @foo b
ERROR: LoadError: ArgumentError: oops.
Stacktrace:
 [1] var"@foo"( __source__ ::LineNumberNode, __module__ ::Module, x::Any)
   @ Main ./REPL[18]:2
in expression starting at REPL[19]:1

```

I can work around that by using `@eval`, but it seems clunky and I have to catch the `LoadError` instead of the `ArgumentError`:

```julia-repl
julia> @test_throws LoadError @eval @foo b
Test Passed
      Thrown: LoadError

```

Is there a better way? I suppose I could split the expression handling into a separate function and test that function instead, but I’d rather there was a more general solution to this.

---

<div class="post-metadata">

**Author:** ![fredrikekre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fredrikekre/32/1688_2.png) [@fredrikekre](https://discourse.julialang.org/u/fredrikekre)\
**Post date:** [July 12, 2024, 11:00pm UTC](https://discourse.julialang.org/t/testing-error-thrown-by-a-macro/116983/2 "2024-07-12T23:00:55Z")

</div>

```julia-repl
julia> @test_throws ArgumentError @macroexpand @foo b
Test Passed
      Thrown: ArgumentError

```

---

<div class="post-metadata">

**Author:** ![Benny](https://avatars.discourse-cdn.com/v4/letter/b/49beb7/32.png) [@Benny](https://discourse.julialang.org/u/Benny)\
**Post date:** [July 13, 2024, 2:14am UTC](https://discourse.julialang.org/t/testing-error-thrown-by-a-macro/116983/3 "2024-07-13T02:14:47Z")

</div>

This is my go-to because I can interpolate stuff easier into an `Expr` instance.

```julia
julia> @test_throws ArgumentError macroexpand(Main, :(@foo b))
Test Passed
      Thrown: ArgumentError

```

Its `@macroexpand` expression does differ a bit in the `macroexpand` line from fredrikekre’s, so I’m not certain it behaves the same generally even though I expect it to.
