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

mockito should store its own object instances instead of shared instances #319

Open
woprandi opened this issue Jan 18, 2021 · 2 comments
Open
Labels
P3 A lower priority bug or feature request type-enhancement A request for a change that isn't a bug

Comments

@woprandi
Copy link

woprandi commented Jan 18, 2021

mockito stores mock's parameters to allow us to check them via captureAny. But the instance's fields may have changed between the mock call and the verify :

final user = User(name: "foo");
...
// Mistake, we called remote service (with a serialization) before changing the name field
apiClient.patchUser(user);
user.name = "bar";
// Testing with a mock apiClient
final user = verify(apiClient.patchUser(captureAny)).single.captured as User;
expect(user.name, "bar")  // Passed, false-positive

I think it makes sense to store a cloned object to make sure it doesn't change between the interaction and the verification. Of course I'm not sure about the side-effect.

@srawlins
Copy link
Member

Interesting case. There is no way to clone an Object of unknown type. We could store the hashCode, in addition to the actual argument which was passed, and then, as you say, do a quick verification step on its way out in .captured.single... This would catch a subset of cases that are like your description, as long as the .name is an input to the hashCode.

@woprandi
Copy link
Author

woprandi commented Jan 19, 2021

Anyway, I think a good practice is to avoid as much as possible mutables objects and always create new instance when possible.
That's what I did after discovering that.
The hashcode check could be an acceptable compromise

@srawlins srawlins added P3 A lower priority bug or feature request type-enhancement A request for a change that isn't a bug labels Jul 26, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
P3 A lower priority bug or feature request type-enhancement A request for a change that isn't a bug
Projects
None yet
Development

No branches or pull requests

2 participants