Tests in doctests

This doctest succeeds:

/// ```
/// #[test]
/// fn test() {
///     assert!(false);
/// }
/// ```
fn foo() {
    
}

playground

How do I run tests in doctests?

Could you provide some context as to why?


Of course you could fake it:

/// ```
/// #[test]
/// # fn fake_test() {}
/// fn test() {
///     assert!(false);
/// }
/// # test();
/// ```
fn foo() {
    
}

The fake_test is there to have something the #[test] attribute applies to, as apparently, the implicit cfg(doctest) from the #[test] attribute otherwise means that test wouldn’t even be compiled at all (as apparent from the not-in-scope errors that would otherwise appear). The # test(); calls the test directly (in the context of the main function doctests implicitly generate).

2 Likes

Sure. I want to write some documentation that includes a test in an example.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.