test-context
A library for providing custom setup/teardown for Rust tests without needing a test harness.
use ;
Alternatively, you can use async functions in your test context by using the
AsyncTestContext.
use ;
The AsyncTestContext works well with async test wrappers like
actix_rt::test or
tokio::test.
async
Attribute order
Place #[test_context(...)] before other test attributes like #[tokio::test] or #[test].
Why: Attributes expand in source order. #[test_context] generates a wrapper and reattaches
the remaining attributes to it. It must run first so the test attribute applies to the wrapper
that runs setup/teardown.
Valid:
async
Invalid:
async
Using AsyncTestContext in sync tests that require Tokio
By default, when you use an AsyncTestContext in a synchronous test (no #[tokio::test]),
this crate runs setup/teardown using the futures executor. If your context calls
Tokio-only APIs (e.g., tokio::time::sleep, timers, or Tokio sockets) during setup/teardown,
enable the optional tokio-runtime feature so those steps run inside a Tokio runtime:
[]
= { = "0.5", = ["tokio-runtime"] }
With this feature, the crate tries to reuse an existing runtime; if none is present, it creates
an ephemeral current-thread Tokio runtime around setup and teardown for sync tests. Async
tests annotated with #[tokio::test] continue to work as usual without the feature.
Skipping the teardown execution
Also, if you don't care about the teardown execution for a specific test,
you can use the skip_teardown keyword on the macro like this:
use ;
Taking ownership of the context vs taking a reference
If the teardown is ON (default behavior), you can only take a reference to the context, either mutable or immutable, as follows:
❌The following is invalid:
If the teardown is skipped (as specified in the section above), you can take an immutable ref, mutable ref or full ownership of the context:
⚠️ Ensure that the context type specified in the macro matches the test function argument type exactly
The error occurs when a context type with an absolute path is mixed with an it's alias.
For example:
✅The following code will work:
use Connection as DbConn;
// or
use Connection
❌The following code will not work:
use Connection as DbConn;
// or
use Connection as DbConn;
Type mismatches will cause context parsing to fail during either static analysis or compilation.
License: MIT