Proposal: safer expectations in idiomatic syntax
See original GitHub issueHi!
I’ve grown a bit frustrated by expectations at the end of the line, methodCall wasCalled once
, because when method signature is long the reader can lose context before they read until wasCalled once
, and worse, in the case of long signatures, it’s so easy to overlook adding (or drop) the verification completely. When verification is missing, the test will happily pass without complaining about anything.
Additionally, when multiple verifications follow each another, they don’t line up as well as they used to, because actual verification clauses are no longer positioned one after another.
It wasn’t the case with vanilla mockito, where expectation comes first (verify(mock).foo(any)
).
Strict mode solves the problem partially, but it isn’t always an option when migrating large projects from older versions of mockito: it’s physically impossible to bring thousands of mocks that have been stubbed for multiple purposes into strict mode.
To help keep verifications safe even in lenient mode, I propose replacing single-step verifications with a macro-based two-step verification.
Instead of
val myMock1 = mock[Service1]
val myMock2 = mock[Service2]
// call tested method
myMock.foo(*, *, *) wasCalled once
myMock2.bar("hello", *, *) wasCalled twice
we’d do this
val myMock1 = mock[Service1]
val myMock2 = mock[Service2]
// call tested method
expect {
myMock.foo(*, *, *) wasCalled once
myMock2.bar("hello", *, *) wasCalled twice
}
The entire verification section of the test should consist of expect
block that would use a macro to fail compilation for every line within the block that is not a verification.
An alternative approach would be to add idiomatic syntax resembling specs2-mockito:
there was one(myMock).foo(*, *, *)
there were two(myMock2).bar("hello", *, *)
or scalamock-style
(myMock.foo _).expect(*, *, *)
What do you think?
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (6 by maintainers)
Top GitHub Comments
Ok, we can do verification as a first step. I’m quite busy at the moment, but will take a look as soon as I finish off some other stuff.
Feel free to raise a PR if you feel like doing it yourself 😃
Okay, I gave it a stab - please take a look when you have time!