-
Notifications
You must be signed in to change notification settings - Fork 63
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
Support for return_const Option<&T> and Result<&T, E> #387
Comments
That would be handy, but there are infinitely many possible structs that might be parameterized on |
I concur - this is a very handy feature to have. |
@asomers in general supporting something like |
That would only work if you want the mock method to return |
Is there now a way to mock a method returning |
@gollth there isn't a way to do it automatically. You'll have to do it at least partly by hand. Perhaps something like this: struct MyStruct<T> {...}
impl<T> MyStruct<T> {
fn foo(&self) -> Option<&T>;
}
mock!{
MyStruct<T: 'static> {
fn _foo(&self) -> Option<T>
}
}
impl<T: 'static> MockMyStruct<T> {
fn foo(&self) -> Option<&T> {
self._foo().as_ref()
}
} |
Thanks for the quick answer @asomers. This would probably work. A colleague of mine suggested another approach, by leaking a struct X; // dummy payload
#[mockall::automock]
trait Foo {
fn foo(&self) -> Option<&X>;
}
#[test]
fn test() {
let mut mock = MockFoo();
let x = Box::leak(Box::new(Some(X)));
mock.expect_foo().return_const(x.as_ref());
// ...
} This works for my use case (non-generic signature). Don't know if this helps for the original question, just thought I post here for reference (= |
Mocking a trait method
fn foo(&self) -> Option<&T>
is difficult because return_const wantsOption<&T>
, so the mock doesn't own the value. It would be more useful if return_const would acceptOption<T>
(similar to a mocked method returning &T) instead so that the expectation can own the T and return a reference to it. I had to use lazy_static to work around this.The text was updated successfully, but these errors were encountered: