Skip to content

Mockall with Any: How to use "self" in returning #395

Answered by asomers
richardzone asked this question in Questions
Discussion options

You must be logged in to vote

The return_once method does not exist for methods that return a non-static reference. Instead, they only have return_const, and the expectation must own the referent. That makes your use case pretty hard. I've never tried to mock a method that needs to return &self. But the following should definitely work:

task.expect_as_any().return_const(MockTask::new());

For unusual requirements, it's often best to manually implement the tricky method, like this for example:

mock!{
    pub OtherTask{
        fn as_any_priv(&self);
    }
}
impl Task for MockOtherTask {
    fn as_any(&self) -> &dyn Any {
        self.as_any_priv();
        self
    }
}

The as_any_priv method only exists so you can still…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@richardzone
Comment options

@asomers
Comment options

@richardzone
Comment options

Answer selected by richardzone
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants