Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot access fields of a newtype-wrapped struct #66

Open
FalkWoldmann opened this issue Dec 17, 2024 · 1 comment
Open

Cannot access fields of a newtype-wrapped struct #66

FalkWoldmann opened this issue Dec 17, 2024 · 1 comment

Comments

@FalkWoldmann
Copy link

FalkWoldmann commented Dec 17, 2024

Hi,

say you have this following struct in a crate A

#[cfg_attr(test, faux::create)]
#[derive(Clone)]
pub struct SpecificRepository(GenericRepository);

#[cfg_attr(test, faux::methods)]
impl SpecificRepository {
    pub fn new(collection: GenericRepository) -> Self {
        Self { 0: collection }
    }

    pub fn get_collection_more_specific(&self) -> String {
        self.0.collection.clone()
    }
}

and GenericRepository is defined in a crate B:

#[cfg_attr(any(test, feature = "testing"), faux::create)]
#[derive(Clone)]
pub struct GenericRepository {
    pub collection: String,
}

#[cfg_attr(any(test, feature = "testing"), faux::methods)]
impl GenericRepository{
    pub fn new(collection: String) -> Self {
        Self { collection }
    }

    pub fn get(&self) -> String {
        self.collection.clone()
    }
}

I am unable to compile the tests, because the compiler cannot find the field collection on type GenericRepository.

#[cfg(test)]
mod tests {
    use faux::when;
    use super::*;

    #[test]
    fn test_do_some_stuff() {
        let mut repo = SpecificRepository::faux();
        let repository = GenericRepository::new("Hello".to_string());
        when!(repo.get_collection_more_specific).then_return(String::from("world"));
        let moin = SpecificService(repo);
        assert_eq!(moin.do_some_stuff(), 5);
    }
}

Compiling in non-test profile works without issue:

fn main() {
    let foo = SpecificService(SpecificRepository::new(GenericRepository::new("Hello".to_string())));
    println!("{}", foo.do_some_stuff());
    println!("Hello, world!");
}
@nrxus
Copy link
Owner

nrxus commented Dec 18, 2024

This is not a bug, albeit I do wish I remember why I removed the check in faux to make it not work on structs with public fields.

If faux is mocking a struct, all of its fields should be private and anyone accessing it should be doing it through methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants