[rust-dev] Using 'mod' for test code

Nathan Typanski ntypanski at gmail.com
Wed Jul 23 13:10:29 PDT 2014


Hey Allen,

I think you've got it backwards. You shouldn't be importing the
regular module from the test one, but hiding the test modules within
the regular one - behind a `#[cfg(test)]` directive.

To apply this to your example, in `myprogram.rs` you should have a line

    #[cfg(test)]
    mod testprogram;

and then in the test file, put `#[test]` above your individual tests.
Then you compile `myprogram.rs` and, when compiled with `--test`, it
compiles in the test code.

Another, arguably more common practice, is to write

    #[cfg(test)]
    mod tests {
        use super::{foo, bar};

        #[test]
        fn test_foo_is_bar {
            assert_eq!(foo(), bar());
        }
    }

For more on testing, check out

<http://www.rustforrubyists.com/book/chapter-04.html>
<http://aturon.github.io/testing/unit.html>

Have fun learning Rust!

        Nathan


More information about the Rust-dev mailing list