Testing Rust Macros: Declarative and Procedural

Testing Rust Macros: Declarative and Procedural

Macros in Rust are notoriously tricky to test because they generate code at compile time. A bug in a macro can produce cryptic error messages or silently incorrect behavior. This guide covers strategies for testing both declarative (macro_rules!) and procedural (#[proc_macro]) macros.

Why Macro Testing Is Hard

Regular functions take values and return values. Testing is straightforward: call the function, assert the output. Macros take tokens and expand to more tokens. Testing means:

  1. Verifying the generated code compiles — does the expansion produce valid Rust?
  2. Verifying the generated code does what you intended — does it behave correctly at runtime?
  3. Verifying compile errors — does the macro produce helpful errors for invalid input?

Each requires different tools.

Testing macro_rules! Macros

Declarative macros are simpler — test them by using them and asserting on runtime behavior.

Basic Usage Tests

macro_rules! max {
    ($x:expr) => ($x);
    ($x:expr, $($rest:expr),+) => {
        std::cmp::max($x, max!($($rest),+))
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_max_single() {
        assert_eq!(max!(5), 5);
    }

    #[test]
    fn test_max_two() {
        assert_eq!(max!(3, 7), 7);
        assert_eq!(max!(7, 3), 7);
    }

    #[test]
    fn test_max_many() {
        assert_eq!(max!(1, 5, 3, 9, 2), 9);
    }

    #[test]
    fn test_max_negative() {
        assert_eq!(max!(-1, -5, -3), -1);
    }
}

The macro expands during compilation. If the expansion is wrong, the test fails at compile time (doesn't compile) or runtime (wrong values).

Testing Macros That Return Different Types

When a macro produces different types based on input, test each variant:

macro_rules! vec_of_strings {
    ($($x:expr),*) => {
        vec![$($x.to_string()),*]
    };
}

#[test]
fn test_empty() {
    let v: Vec<String> = vec_of_strings![];
    assert!(v.is_empty());
}

#[test]
fn test_mixed_types() {
    let v = vec_of_strings![1, "hello", 3.14_f64];
    assert_eq!(v, vec!["1", "hello", "3.14"]);
}

Testing Macro Hygiene

Hygiene ensures macro-introduced variables don't conflict with user code. Test this explicitly:

macro_rules! swap {
    ($a:expr, $b:expr) => {
        let temp = $a;
        $a = $b;
        $b = temp;
    };
}

#[test]
fn test_swap_no_hygiene_conflict() {
    let mut a = 1;
    let mut temp = 99;  // Should not conflict with macro's `temp`
    
    swap!(a, temp);
    
    // If hygiene is broken, this might give wrong results
    assert_eq!(a, 99);
    assert_eq!(temp, 1);
}

If your macro has hygiene issues, this test will fail in non-obvious ways.

Using macro-expand to Inspect Expansions

Install cargo-expand to see what your macros expand to:

cargo install cargo-expand

# See expansion of entire file
cargo expand

# See expansion of a specific module
cargo expand tests

This isn't automated testing, but it's invaluable for debugging. When a macro behaves unexpectedly, expand it to see the actual generated code.

Testing Procedural Macros

Procedural macros are more complex — they're full Rust programs that manipulate token streams. Testing them requires testing the generated code's behavior and the error messages they produce.

Project Structure

Proc macros must live in their own crate:

myapp/
├── Cargo.toml
├── myapp-macros/
│   ├── Cargo.toml
│   └── src/
│       └── lib.rs
└── src/
    └── lib.rs
# myapp-macros/Cargo.toml
[lib]
proc-macro = true

[dependencies]
syn = { version = "2", features = ["full"] }
quote = "1"
proc-macro2 = "1"

[dev-dependencies]
trybuild = "1"

Testing the Happy Path

The simplest proc macro test uses the macro and asserts on generated behavior:

// myapp-macros/src/lib.rs
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(Builder)]
pub fn derive_builder(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;
    
    let expanded = quote! {
        impl #name {
            pub fn builder() -> #name Builder {
                #name Builder::default()
            }
        }
    };
    
    expanded.into()
}

Test in the consuming crate:

// src/lib.rs or tests/derive_tests.rs
use myapp_macros::Builder;

#[derive(Builder, Default)]
struct Request {
    url: String,
    timeout: u32,
}

#[test]
fn test_builder_method_generated() {
    let _builder = Request::builder();
    // If the derive generated code incorrectly, this wouldn't compile
}

The test passing means the generated code compiled successfully. That's often the most important assertion.

trybuild for Compile-Error Tests

trybuild is the standard tool for testing that your proc macros produce the correct compile errors for invalid inputs.

[dev-dependencies]
trybuild = "1"

Create test files that should fail to compile:

myapp-macros/
└── tests/
    ├── ui/
    │   ├── pass/
    │   │   └── basic_derive.rs
    │   └── fail/
    │       ├── not_a_struct.rs
    │       └── missing_required_field.rs
    └── ui_tests.rs
// tests/ui_tests.rs
#[test]
fn ui() {
    let t = trybuild::TestCases::new();
    t.pass("tests/ui/pass/*.rs");
    t.compile_fail("tests/ui/fail/*.rs");
}
// tests/ui/fail/not_a_struct.rs
use myapp_macros::Builder;

#[derive(Builder)]
enum MyEnum {  // Builder only works on structs
    Variant,
}

fn main() {}

Run cargo test. trybuild compiles each file and compares the error output to a .stderr snapshot file. On first run, it creates the snapshots. On subsequent runs, it verifies errors match.

tests/ui/fail/not_a_struct.stderr:
error: Builder can only be derived for structs
 --> tests/ui/fail/not_a_struct.rs:4:10
  |
4 | #[derive(Builder)]
  |          ^^^^^^^

If your error message changes, trybuild fails — you intentionally update the snapshot to approve the change.

Updating trybuild Snapshots

When you intentionally change error messages:

TRYBUILD=overwrite cargo test

This regenerates all .stderr files. Review the changes and commit them.

Testing Token Stream Transformations

For testing the output tokens directly (without compiling), use prettyplease and string comparison:

// In macro tests
use proc_macro2::TokenStream;
use quote::quote;

fn format_tokens(tokens: TokenStream) -> String {
    let file: syn::File = syn::parse2(tokens).unwrap();
    prettyplease::unparse(&file)
}

#[test]
fn test_builder_expansion() {
    let input: syn::DeriveInput = syn::parse_quote! {
        struct Request {
            url: String,
            timeout: u32,
        }
    };
    
    // Call your internal expansion function (not the proc_macro entry point)
    let expanded = derive_builder_impl(&input);
    
    let formatted = format_tokens(expanded);
    
    // Assert specific parts of the expansion
    assert!(formatted.contains("impl Request"));
    assert!(formatted.contains("pub fn builder()"));
}

This requires splitting your macro logic into an internal function that takes syn::DeriveInput and returns proc_macro2::TokenStream, making it testable without the proc macro boundary.

Pattern: Testable Macro Internals

Refactor your proc macro to separate the logic from the proc macro entry point:

// myapp-macros/src/lib.rs
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;

// Public entry point (hard to test)
#[proc_macro_derive(Builder)]
pub fn derive_builder(input: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(input as syn::DeriveInput);
    derive_builder_impl(input)
        .unwrap_or_else(|e| e.to_compile_error())
        .into()
}

// Internal function — fully testable
fn derive_builder_impl(input: syn::DeriveInput) -> syn::Result<TokenStream2> {
    let name = &input.ident;
    
    // Validate input
    match &input.data {
        syn::Data::Struct(_) => {},
        _ => return Err(syn::Error::new_spanned(
            &input.ident,
            "Builder can only be derived for structs"
        )),
    }
    
    Ok(quote::quote! {
        impl #name {
            pub fn builder() -> Self {
                Default::default()
            }
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_rejects_enum() {
        let input: syn::DeriveInput = syn::parse_quote! {
            enum MyEnum { Variant }
        };
        
        assert!(derive_builder_impl(input).is_err());
    }
    
    #[test]
    fn test_generates_builder_method() {
        let input: syn::DeriveInput = syn::parse_quote! {
            struct Request { url: String }
        };
        
        let result = derive_builder_impl(input);
        assert!(result.is_ok());
        
        let output = result.unwrap().to_string();
        assert!(output.contains("fn builder"));
    }
}

This pattern lets you unit test the logic without trybuild overhead.

Testing Attribute Macros

Attribute macros work the same way as derive macros for testing:

#[proc_macro_attribute]
pub fn log_calls(attr: TokenStream, item: TokenStream) -> TokenStream {
    // instrument function with logging
}

Test via trybuild for compile errors, and integration tests for runtime behavior:

#[log_calls]
fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[test]
fn test_function_still_works() {
    // If the attribute macro broke the function signature, this fails
    assert_eq!(add(2, 3), 5);
}

Common Macro Testing Checklist

For any new macro, cover:

  • Happy path — basic valid input works
  • All supported variants — struct vs tuple struct vs unit struct, etc.
  • Edge cases — empty inputs, single items, large inputs
  • Error cases (trybuild) — invalid input produces clear error messages
  • Hygiene — macro-introduced identifiers don't conflict with user code
  • Expansion correctness — inspect with cargo expand for complex macros

Continuous Testing in CI

Proc macro tests are just regular cargo test tests, so CI needs no special setup:

- name: Test
  run: cargo test --all

The --all flag runs tests for all workspace members including your macro crate.

For large macro test suites with many trybuild files, test compilation can be slow. Consider running macro tests in a separate CI job to parallelize:

jobs:
  unit-tests:
    runs-on: ubuntu-latest
    steps:
      - run: cargo test --lib --bins

  macro-tests:
    runs-on: ubuntu-latest
    steps:
      - run: cargo test --test ui_tests

Summary

Testing Rust macros requires different strategies for different concerns:

  • Runtime behavior tests — use the macro and assert on output, like any normal test
  • Compile error tests — use trybuild with .stderr snapshots to verify error messages
  • Expansion tests — split macro logic into an internal function testable without proc macro plumbing
  • cargo expand — manually inspect expansions when debugging unexpected behavior

The most important rule: macros that only "look right" are not tested. A macro needs a test that would fail if you introduced a bug in the expansion logic.

Read more

Start now free