nrxus / faux

Struct mocking library for Rust
https://nrxus.github.io/faux/
MIT License
411 stars 14 forks source link

Is my code too complex? #61

Closed Mrodent closed 2 months ago

Mrodent commented 2 months ago

Me again... your example works, as I said.

But when I put faux = "0.1.10" under [dependencies] and then try to use these "faux" directives on my own code (a much simplified testing example for the real app I'm developing), I get a problem error just by the first step, i.e. putting #[faux: create] in front of the struct, like so:

#[faux::create]
pub struct HandlingFramework {
    pub index_name: String
}

pub trait TextDocument {}

impl HandlingFramework {
    pub fn new(index_name: String, _gather_closure: &dyn Fn(WalkDir, &Weak<HandlingFramework>) -> Result<HashMap<String, Box<dyn TextDocument>>>, 
        ) -> Rc<Self> {
    println!("preparing to create index {index_name}");
        Rc::new_cyclic(|_this: &std::rc::Weak<HandlingFramework>|
        HandlingFramework { 
        index_name,
        }
        // HandlingFramework( 
        //  index_name,
        // )
    )
    }
    pub fn create_index(&self) -> Result<usize> {
        ...

... this use of Rc::new_cyclic to create a HandlingFramework is unfortunately necessary. So the struct has to be constructed inside that closure.

I get this error:

error[E0560]: struct `HandlingFramework` has no field named `index_name`
  --> src\handling_framework.rs:43:6
   |
28 | pub struct HandlingFramework {
   |            ----------------- `HandlingFramework` defined here
...
43 |                  index_name,
   |                  ^^^^^^^^^^ field does not exist
   |
help: `HandlingFramework` is a tuple struct, use the appropriate syntax
   |
42 |             HandlingFramework(/* fields */)

... the field certainly does exist, and HandlingFramework is not a "tuple struct" (!) and the compiler's suggestion did not work (see attempt commented out in the above code block).

Do you have any explanation for this odd result (all I've done so far is put #[faux::create] over pub struct HandlingFramework)?

nrxus commented 2 months ago

It looks like your impl block is missing the faux::methods attribute. If you want to be able to use the inner fields of a mocked struct then it needs to be in an impl block where faux::methods is specified. This is because faux::create changes the insides of your struct to make it mockable so those fields aren't as accessible anymore.

nrxus commented 2 months ago

I am closing this but lmk if you are still having issues