nrxus / faux

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

How to handle non-cloneable result types #55

Closed giomf closed 11 months ago

giomf commented 11 months ago

Hi,

This is more of a question than a real issue. I want to use faux to mock a method that has anyhow::Result as return value. The main problem is that anyhow::Error does not implement Clone.

The following line of code unfortunately throws me a compiler error.:

         when!(mock.read_by_gh_id(_)).then_return(Ok(Some(User::default())))
                                      ^^^^^^^^^^^ the trait `Clone` is not implemented for `anyhow::Error`

As a workaround I currently use the following line: when!(mock.read_by_gh_id(_)).then(|_| Ok(Some(User::default())))

Unfortunately this is a bit uncomfortable in the long run.

Is there perhaps a better solution here?

nrxus commented 11 months ago

For mocks that only need to be called once you can do when!(mock.read_by_gh_id).once().then_return(/*your result*/).

This works because once() returns a type that knows it will only be called once so it doesn't need to clone the return object at all. If the mock does get called more than once though, then the second time you call it the test will fail saying that the mock was exhausted.

Docs: https://docs.rs/faux/latest/faux/struct.When.html#method.once and https://docs.rs/faux/latest/faux/when/struct.Once.html#method.then_return

giomf commented 11 months ago

This works for me! Thanks. Don't know how I missed that.