Conditional module import

Any way I can import modules depend on #[cfg(test)]? Some sort like this:

#[cfg(test)]
use test::Foo;
#[!cfg(test)]
use real::Foo;

The reason I want this is that real::Foo is very hard to constructing, and it has nothing to do with testing, a simple version of Foo is helpful for writing test cases. Generic type can do this, but I don't want my code to be that complicated.

If you change this to #[cfg(not(test))], it'll work, I think.

2 Likes

If possible, you should probably try to use generics and dependency injection instead of monkey-patching your code's imports to swap Foo out for a dummy version during testing.

That approach tends to be more maintainable in the long run because you won't need to update test::Foo every time real::Foo's API changes. It'll also help avoid situations during testing where one part of the codebase uses test::Foo and another uses real::Foo, and you run into "Found test::Foo but expected real::Foo" errors.

1 Like

It'll also help avoid situations during testing where one part of the codebase uses test::Foo and another uses real::Foo, and you run into "Found test::Foo but expected real::Foo" errors

That's exactly what I jsut met, I didn't know that the compiler also checks codes unrelated with test cases, so at last I choose to use gnerics.

1 Like

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.