We can create tests in one of the two ways: either by adding a tests directory with a lib.rs file or by simply adding a file with the tests for that module. As we are already using a directory structure, let's stay with that for the unit tests.
As previously discussed in Chapter 1, Introducing and Installing Rust, to add a unit test, we precede the code with the following:
#[test]
Then to build, we need to do the following:
cargo test
When we do this, though, we hit a problem. Our unit test file looks like this:
extern crate mathslib; use mathsLib::conversions::temperature; #[cfg(test)] mod temperature_tests { #[test] fn test_kelvin_to_celcius_pass() { let calc = kelvin_to_celcius(14.5); assert_eq!(calc.0, true); } #[test] #[should_panic(expected = "assertion failed")] fn test_kelvin_to_celcius_fail() { let calc = kelvin_to_celcius(-4f32); assert_eq!(calc.0,true); } }
On the face of it, this should work, but it comes back with something that is somewhat perplexing:
This doesn't make sense; we know there is a module called Temperature, so why are we getting this message? The answer is that it's all down to the privacy of the module and functions.