Skip to content
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

Mocking spawn (i.e. for tokio runtime) #96

Closed
MOZGIII opened this issue Dec 21, 2019 · 3 comments
Closed

Mocking spawn (i.e. for tokio runtime) #96

MOZGIII opened this issue Dec 21, 2019 · 3 comments
Labels
question Usage question

Comments

@MOZGIII
Copy link

MOZGIII commented Dec 21, 2019

With this trait:

pub trait Runtime: Clone + Send + Sync + Unpin + Debug {
    fn spawn<F>(&self, future: F)
    where
        F: Future<Output = ()> + Send + 'static;
}

How do I mock spawn?

I tried like this:

let mock = MockRuntime::new();
mock.expect_spawn().returning(|_| ());
mock
   |
xx |             mock.expect_spawn().returning(|_| ());
   |                                            ^ consider giving this closure parameter a type
@asomers
Copy link
Owner

asomers commented Dec 21, 2019

In this case spawn is a generic method, which really means it's an infinite collection of nongeneric methods. You must set the expectation for the right version of spawn, or else the call won't match. Assuming you're going to spawn a BoxFuture, you can do that like this. Unfortunately, some Future types can be very long and hard to name. There's no easy solution to the problem of figuring out a Future's true type.

mock.expect_spawn::<BoxFuture<u32, ()>>().returning(|_| ());

Also, in this example you could use return_const(()) instead of returning(|_| ()), but that won't fix the type problem.

@asomers asomers added the question Usage question label Dec 21, 2019
@MOZGIII
Copy link
Author

MOZGIII commented Dec 22, 2019

The problem is I'm using it with async fn, so it's flat out impossible to just name, afaik.
Good thing is I could implement the trait myself, and add a mocked method that's non-generic and simply receives the non-generic BoxFuture. This is far from perfect, but it works.

So, the issue is essence is really not about the Futures, but rather about taking compiler generated types, like Fn, FnMut, FnOnce and Future that can't be addressed any way other than impl ....
I think it's worth creating a dedicated issue for this more generic thing.

@asomers
Copy link
Owner

asomers commented Oct 2, 2020

I think this problem could be elegantly solved by #217 .

@asomers asomers closed this as completed Oct 2, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Usage question
Projects
None yet
Development

No branches or pull requests

2 participants