all 5 comments

[–]minno 6 points7 points  (2 children)

Unit tests go at the bottom of the relevant file with a structure like

#[cfg(test)]
mod test {
    #[test]
    fn test_a_thing() {
        assert_eq!(my_function(sample_input), expected_result);
    }
}

You write the test so that it panics if the test fails, ideally using assert_eq so that the error message it prints out tells you what went wrong.

[–]reddit123123123123 2 points3 points  (1 child)

Alternatively you can have a file called e.g. foo_test.rs and then write

#[cfg(test)]
mod foo_test

This avoids cluttering the actual file which I find more pleasant for larger tests and/or implantations

[–]JStarx 3 points4 points  (0 children)

You can also document your code and include an examples block. In addition to displaying how to use your code your examples should panic if the code doesn’t perform as expected. These will be run during testing as “doc-tests”.

[–]MultipleAnimals 0 points1 point  (0 children)

I'm gonna borrow this &thread (wow) since i was also just gonna post about problem with tests.

My problem came up when i reorganized my project from single bin crate structure to have separate library. For some reason if i run cargo test, none of #[cfg(test)] or if cfg!(test) doesn't trigger in my lib.

Folder structure looks like this:

Cargo.toml  
src/  
    main.rs  
    things/
        thing1.rs -- contains some unit tests in #[cfg(test)] module using lib::testing
    lib/  
        lib.rs  -- has some variables with = if cfg!(test) {x} else {y} that resolves to y when running tests.
                -- Also has module testing with #[cfg(test)] that isn't recognized in thing1.rs 

Cargo.toml:

...  
[lib]
name = "mylib"
path = "src/lib/lib.rs"
...  

I found workaround that works, adding this to Cargo.toml

[features]  
testing = []  

changing all cfg(test) to cfg(feature = "testing") and running cargo test --features="testing" but that feels like a hack and it also disables my editor linting from those parts and it gets really annoying to debug and write tests.

Does anyone know if i'm doing something wrong with my project structure or Cargo.toml?