-
I have some code that started off looking like this: use std::thread; I want to be able to unit test foo() and mock out thread::spawn() so I modified foo() like this pub fn foo() -> bool and in my test code I have: test_fn() { but when I run cargo test I get I think this is because I don't have the parameter types correct. The u32 I added in response to the compiler complaints but I really don't care what type T is. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 21 replies
-
That's because the mock! {
pub Thread {
pub fn spawn<T: 'static>(f: Box<FnOnce() -> T> + 'static) -> JoinHandle<T>;
}
} then box your closure when you call spawn. But if you really don't want to box closures in production, then you can work around it by defining your mocks like this: mock! {
pub Thread {
pub fn _spawn<T: 'static>(f: Box<FnOnce() -> T> + 'static) -> JoinHandle<T>;
}
}
impl MockThread {
pub fn spawn<F, T>(f: F) -> JoinHandle
where F: FnOnce -> T + Send + 'static,
T: Send + 'static
{
self._spawn(Box::new(f))
}
} that way you can write expectations that will take a boxed closure, but your production code won't need to do the boxing. |
Beta Was this translation helpful? Give feedback.
That's because the
F
parameter is a closure, which is impossible to name. And that makes it impossible to create an expectation for it. You could try this instead:then box your closure when you call spawn. But if you really don't want to box closures in production, then you can work around it by defining your mocks like this: