Test setup for doctests

I'm working on an HTTP client, and I'd like to do some early setup for my doctests to override networking behavior, so all traffic stays local to the host and talks to a fake backend. Is there a common idiom or best practice for this? Right now it seems like my best option is to define an undocumented doctest_setup(), and call to it from the beginning of each doctest in a /// # line.

I think maybe you can also annotate your function with #[cfg(test)] so it only gets compiled for tests, but otherwise doesn't pollute your code.

1 Like

AFAIK test is not set for doctests, you need to use cfg(doctest). For example: Redirecting...


Thanks. "I have approximate knowledge of many things."

1 Like

Normally I'd make these sorts of things integration tests and put them in the tests/ folder because they involve non-trivial things like spinning up a server.

For demonstration purposes you can add the no_run attribute to a doctest so cargo test makes sure the code compiles, but doesn't actually run it (avoiding the need to pollute your doc test with setup code).


Ooh, that's a good idea, thanks! Do you happen to know if there's any tooling to automatically extract the doctests into a .rs file that I could then check into tests/?

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.