Mockall with Any: How to use "self" in returning #395
-
Apologies for bother again, but here's the thing I'd like to achieve: use std::any::Any;
use mockall::{automock, mock, predicate::*};
#[automock]
pub trait Task {
fn execute(&self) -> Result<(), Box<dyn std::error::Error>>;
fn as_any(&self) -> &dyn Any;
}
mock!{
pub OtherTask{}
impl Task for OtherTask {
fn execute(&self) -> Result<(), Box<dyn std::error::Error>>;
}
}
impl Task for MockOtherTask {
fn as_any(&self) -> &dyn Any {
self
}
}
struct RealTask;
impl Task for RealTask {
fn execute(&self) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn as_any(&self) -> &dyn Any {
self
}
}
pub fn get_task<T: Task + Any>(tasks: &[Box<dyn Task>]) -> Option<&T> {
tasks
.iter()
.find_map(|task| task.as_any().downcast_ref::<T>())
}
#[test]
fn test() {
let task = MockTask::new();
let other_task = MockOtherTask::new();
let tasks: Vec<Box<dyn Task>> = vec![Box::new(task), Box::new(other_task)];
// How do I return self like in RealTask?
task.expect_as_any().return_var(task);
// Test whether get_task can get the correct item of Task from tasks
assert_eq!(get_task::<MockTask>(&tasks).type_id(), Some(&task).unwrap().type_id());
} I have trouble trying to get above to compile. The error is pretty weird, as it seems like it cannot find returning_st or return_once:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
The 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 |
Beta Was this translation helpful? Give feedback.
The
return_once
method does not exist for methods that return a non-static
reference. Instead, they only havereturn_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:For unusual requirements, it's often best to manually implement the tricky method, like this for example:
The
as_any_priv
method only exists so you can still…