Expand description
A library for providing custom setup/teardown for Rust tests without needing a test harness.
use test_context::{test_context, TestContext};
struct MyContext {
value: String
}
impl TestContext for MyContext {
fn setup() -> MyContext {
MyContext { value: "Hello, world!".to_string() }
}
fn teardown(self) {
// Perform any teardown you wish.
}
}
#[test_context(MyContext)]
#[test]
fn test_works(ctx: &mut MyContext) {
assert_eq!(ctx.value, "Hello, world!");
}Alternatively, you can use async functions in your test context by using the
AsyncTestContext.
use test_context::{test_context, AsyncTestContext};
struct MyAsyncContext {
value: String
}
impl AsyncTestContext for MyAsyncContext {
async fn setup() -> MyAsyncContext {
MyAsyncContext { value: "Hello, world!".to_string() }
}
async fn teardown(self) {
// Perform any teardown you wish.
}
}
#[test_context(MyAsyncContext)]
#[test]
fn test_works(ctx: &mut MyAsyncContext) {
assert_eq!(ctx.value, "Hello, World!");
}The AsyncTestContext works well with async test wrappers like
actix_rt::test or
tokio::test.
use test_context::{test_context, AsyncTestContext};
struct MyAsyncContext {
value: String
}
impl AsyncTestContext for MyAsyncContext {
async fn setup() -> MyAsyncContext {
MyAsyncContext { value: "Hello, world!".to_string() }
}
async fn teardown(self) {
// Perform any teardown you wish.
}
}
#[test_context(MyAsyncContext)]
#[tokio::test]
async fn test_async_works(ctx: &mut MyAsyncContext) {
assert_eq!(ctx.value, "Hello, World!");
}§Attribute order
Attribute order matters. Always place #[test_context(...)] before other test attributes
like #[tokio::test] or #[test].
Why: Rust expands attributes in source order. #[test_context] wraps your function and
re-attaches the remaining attributes to the wrapper; it must run first so the test attributes
apply to the wrapper that performs setup/teardown.
Valid:
#[test_context(MyAsyncContext)]
#[tokio::test]
async fn my_test(ctx: &mut MyAsyncContext) {}Invalid:
#[tokio::test]
#[test_context(MyAsyncContext)]
async fn my_test(ctx: &mut MyAsyncContext) {}§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 test_context::{test_context, TestContext};
struct MyContext {}
impl TestContext for MyContext {
fn setup() -> MyContext {
MyContext {}
}
}
#[test_context(MyContext, skip_teardown)]
#[test]
fn test_without_teardown(ctx: &mut MyContext) {
// Perform any operations that require full ownership of your context
}Re-exports§
pub use futures;
Traits§
- Async
Test Context - The trait to implement to get setup/teardown functionality for async tests.
- Test
Context - The trait to implement to get setup/teardown functionality for tests.
Attribute Macros§
- test_
context - Macro to use on tests to add the setup/teardown functionality of your context.