I tried to write a unit test in rust, but when I run cargo test I get the following error: "use of undeclared type Rating". In the src/main.rs file I have defined the struct Rating like this:
#[derive(PartialEq, Debug, Clone, Copy)]
struct Rating(i8);
impl Rating {
pub fn new(value: i32) -> Result <Rating, CreationError> {
match value {
v if v > 10 => Err(CreationError::PosOverflow),
v if v < -10 => Err(CreationError::NegOverflow),
_ => Ok(Rating(value as i8)),
}
}
}
My test file tests/test.rs looks like this:
#[cfg(test)]
fn create_new_rating() {
assert_eq!(Rating::new(10).0, 10);
}
In the Rust documentation I only found examples where libs are tested but not binarys. Do I have to use a different syntax in this case?
Your tests folder is for integration tests, and needs to use your crate as though it were an external user. Add use mycratename::Rating to the top of the test.rs, and make Rating public.
If this is a unit test (which this looks like), it is idiomatic to put tests in the same file as the code. This is described in the Book. You would end up with something like:
#[derive(PartialEq, Debug, Clone, Copy)]
struct Rating(i8);
impl Rating {
pub fn new(value: i32) -> Result <Rating, CreationError> {
match value {
v if v > 10 => Err(CreationError::PosOverflow),
v if v < -10 => Err(CreationError::NegOverflow),
_ => Ok(Rating(value as i8)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_new_rating() {
assert_eq!(Rating::new(10).0, 10);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With