Skip to content

blockjoy/test-macros

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

test-macros

Helper macros for righting clean tests

Example

use test_macros;

fn setup_db() {
    // Create test data, load env etc.
}

fn cleanup_db() {
    // Delete data from tables, close connections etc.
}

#[test]
#[before(call = "setup_db")]
#[after("cleanup_db")]
fn some_test() {
    // … your stuff goes here …
}

before proc macro

Call a function BEFORE a test has run. Useful for e.g. DB setup

Example

fn setup_db() -> &'static str {
    // Create test data, load env etc.

    "Return value, stored in variable '_before_values'"
}

#[test]
#[before(call = "setup_db")]
fn some_test() {
    // … your stuff goes here …
}

Variable '_before_values'

As shown in the setup_db fn example, the return value of the before fn can be used inside the test by using the variable name _before_values

fn setup_db() -> &'static str {
    // Create test data, load env etc.

    "Return value!"
}

#[test]
#[before(call = "setup_db")]
fn some_test() {
    assert_eq!(_before_values, "Return value!") // Asserts positively
}

after proc macro

Call a function AFTER a test has run. Useful for e.g. DB cleanup

Example

fn cleanup_db() {
    // Delete data from tables, close connections etc.
}

#[test]
#[after(call = "cleanup_db")]
fn some_test() {
    // … your stuff goes here …
}

Use with other macros

In the integration test it came up, the order of macros sometimes matters:

#[before(call = "before_fn")]
#[after(call = "after_fn")]
#[tokio::test]
async fn some_async_test() {
    // works well
}
#[tokio::test]
#[before(call = "before_fn")]
#[after(call = "after_fn")]
async fn some_async_test() {
    // marks macro 'after' as unreachable
}

About

Helper macros for writing clean tests

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages