Looking for a workaround for an FnOnce parameter with a non-static lifetime #613
-
I have an trait with a function like:
I understand that automock can't handle the 'a lifetime, and my attempts to use the mock macro suggest that approach won't work either. A few points about my use:
So, my question isn't can I mock this, because I'm pretty sure the answer is no. My question is whether there's any way I can work around the issue without going to a static lifetime. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Is this function part of a public trait, part of a trait that you control, or not part of a trait at all? In the latter two cases, you can conditionally redefine the fuction to use mock!{
pub MyStuct {
fn __eval<T> -> Result<T, EvalError>;
}
}
impl MockMyStruct {
fn eval<'a, T, F>(&self, formula: F) -> Result<T, EvalError>
where
F: 'a + FnOnce() -> Result<T, Box<dyn std::error::Error>>
{
self.__eval()
}
} |
Beta Was this translation helpful? Give feedback.
Is this function part of a public trait, part of a trait that you control, or not part of a trait at all? In the latter two cases, you can conditionally redefine the fuction to use
'static
during#[cfg(test)]
only. That's what I do in similar cases.Another option is to use
mock!
to define a helper function that doesn't have the lifetime, like and then manually define a compliant mock method that wraps the helper. It's more work, but it will at least allow you to write expectations that your closure was called. For example: