Skip to main content

test

Attribute Macro test 

Source
#[test]
Expand description

Marks a test which may have non fatal assertions.

Annotate tests the same way ordinary Rust tests are annotated:

#[test_that::test]
fn should_work() {
   ...
}

The test function is not required to have a return type. If it does have a return type, that type must be test_that::Result. One may do this if one wishes to use both fatal and non-fatal assertions in the same test. For example:

#[test_that::test]
fn should_work() -> TestResult<()> {
    let value = 2;
    expect_that!(value, gt(0));
    verify_that!(value, eq(2))
}

This macro can be used with #[should_panic] to indicate that the test is expected to panic. For example:

#[test_that::test]
#[should_panic]
fn passes_due_to_should_panic() {
    let value = 2;
    expect_that!(value, gt(0));
    panic!("This panics");
}

Using #[should_panic] modifies the behaviour of #[test_that::test] so that the test panics (and passes) if any non-fatal assertion occurs. For example, the following test passes:

#[test_that::test]
#[should_panic]
fn passes_due_to_should_panic_and_failing_assertion() {
    let value = 2;
    expect_that!(value, eq(0));
}

This integrates with other common test attribute macros such as tokio::test and rstest. Just apply both attribute macros to your test.

#[test_that::test]
#[rstest]
#[case(1)]
#[case(2)]
#[case(3)]
fn rstest_works_with_test_that(#[case] value: u32) -> Result<()> {
    verify_that!(value, gt(0))
}

#[test_that::test]
#[tokio::test]
async fn tokio_works_with_test_that() -> Result<()> {
    verify_that!(get_some_value_async().await, gt(0))
}

Note: In the case of rstest, make sure to put #[test_that::test] before #[rstest]. Otherwise the annotated test will run twice, since both macros will attempt to register a test with the Rust test harness.