-
Notifications
You must be signed in to change notification settings - Fork 3
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
Can't mock methods with generic parameters more than once per mock object #55
Comments
I've found a workaround, but it's ugly. The basic idea is to dynamically generate a method name based on the generic parameters. It adds a bunch of ugly code to the user's Mock implementation, however. Worse, it adds an extra method call per generic parameter used to the user's test method (the latter could be eliminated if fn generic_parameters2() {
struct AMock {
e: Expectations,
m: HashMap<any::TypeId, &'static str>
}
impl AMock {
fn new() -> Self {
Self {
e: Expectations::new(),
m: HashMap::new()
}
}
fn expect_foo<T: 'static>(&mut self) -> Method<T, T> {
let m = self.m.get(&any::TypeId::of::<T>()).unwrap();
self.e.expect::<T, T>(m)
}
fn expect_foo_type<T: 'static>(&mut self, name: &'static str) {
self.m.insert(any::TypeId::of::<T>(), name);
}
fn foo<T: 'static>(&self, t:T) -> T {
let m = self.m.get(&any::TypeId::of::<T>()).unwrap();
self.e.was_called_returning::<T, T>(m, t)
}
fn then(&mut self) -> &mut Self {
self.e.then();
self
}
}
let mut mock: AMock = AMock::new();
mock.expect_foo_type::<i16>("foo_i16");
mock.expect_foo_type::<u32>("foo_u32");
mock.expect_foo::<i16>().called_once().with(-1).returning(|_| -1);
mock.expect_foo::<u32>().called_once().with(1).returning(|_| 0);
mock.foo::<i16>(-1);
mock.foo::<u32>(1);
} |
Hey Alan - wow, that's quite a workaround! A goal with simulacrum was to not have to modify the existing struct's method signatures, so that last point in particular is a hassle. Still, I appreciate you bringing this workaround to my attention. |
If you change |
Wow, that is such a simple solution, can't believe I didn't see that before! Thanks for the suggestion. I've put a couple of hours on my calendar tomorrow to spend some time maintaining simulacrum, so hopefully I'll be able to integrate your pull request from June as well as see about fixing this. |
Ok, as of 872b48d, |
This allows simplifying the workaround for issue 55. pcsm/simulacrum#55
Using the low-level technique, I can create mocks for structs with methods that have generic parameters. In different testcases, I can create expectations with different type arguments. However, I cannot create a single testcase that has multiple expectations for the same method with different type parameters. When I try, I get a
panicked at 'called Option::unwrap() on a None value'
error. Here's some example code:The text was updated successfully, but these errors were encountered: