Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Types defined in src/main.rs are not recognized in tests/test.rs file

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?

like image 229
Simon Rechermann Avatar asked Nov 29 '25 18:11

Simon Rechermann


1 Answers

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);
    }
}
like image 200
ddulaney Avatar answered Dec 02 '25 11:12

ddulaney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!