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

Question: support interior mutability for mocks? #385

Open
mattklein123 opened this issue May 25, 2022 · 2 comments
Open

Question: support interior mutability for mocks? #385

mattklein123 opened this issue May 25, 2022 · 2 comments
Labels
enhancement New feature or request

Comments

@mattklein123
Copy link

I just started with the library and quickly came across #191. Would you ever reconsider officially supported interior mutability for mock objects (allowing thread safe access to expectations/calls via &self)?

I have long lived mocks that I want to pass into objects under test. Without considering mocking, I would be able to just move objects inside. To avoid using unsafe code, I can put the object inside an Arc, however per the other issue we can't get mutable access though the Arc.

The proposed solution to pass in a Mutex is undesirable IMO because it forces the code under test to use a mutex when it otherwise would not (I'm not thrilled about having to use an Arc when I otherwise would not but I can live with that.)

From a very quick look at the generated code it looks like most things are already guarded by a mutex, so it seems like supporting interior mutablity, potentially as an option, wouldn't be too difficult?

Mostly just curious if this is something you would consider supporting in the future.

Thanks for the cool library!

@asomers
Copy link
Owner

asomers commented May 25, 2022

I think the "set expectations before passing the object to the code under test" approach is usually the best approach. At least, that's usually what I do. But I can see how that wouldn't work if you have very long-lived mock objects.

@asomers asomers added the enhancement New feature or request label May 25, 2022
@mattklein123
Copy link
Author

Thanks for the response. Yes in general I agree with that approach, but sometimes for better tests I prefer to set expectations in sequence to make sure they only happen after certain events occurs, which makes the set before approach a bit brittle.

FWIW I'm using this horrendous hack right now:

fn mut_mock<T>(mock: &mut Arc<T>) -> &mut T {
  let ptr: *mut T = Arc::as_ptr(mock) as *mut T;
  unsafe { ptr.as_mut().unwrap() }
}

This "works" and is "safe" from my quick read of the code but obviously it would be nice to have this be built in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants