The built-in feature for creating mocks by example saves time when it comes to tiresome set up of arrangements.
This functionality allows you to create mocks of a certain class (the system under test) and in the same time to arrange their behavior.
Let's take the following system under test for example:
For simple tests with few arrangements, this provides only marginal benefit. The real benefit comes with complex tests with multiple
arrangements, like the following:
When creating mock by example, this can easily be rewritten like this:
The new syntax reflects the hierarchical structure of the complex arrangement much better and makes trivial arrangements
(like for the values of properties) easy.
Let's brake it down a bit for better explanation:
It might take a while to wrap one’s mind around the new syntax, but once that is over with, you’ll notice a boost in the
speed with which you produce new tests.
The mocks by example support the using of argument matchers in method arguments, just like in regular Mock.Arrange() expressions.
You can even refer to the arguments of the method when specifying its return value, like so:
In the above example the Param._1 and Param._2 bits are placeholders for the
actual arguments passed to the arranged method. Here it means: call the Object.Equals method with the
first and second arguments passed to cmp.Equals(…).
Additional notes, pitfalls and tricks:
The arranged expression must always be on the left side of the == operator and the implementation – on the right.
The feature is available in both JustMock and JustMock Lite (JML). In JustMock, with the profiler enabled, you can create arrangements
that require elevated mocking.
If the type of a parameter is not one of the supported types (most commonly occurring non-generic types, like int, string, etc.),
specify the type of the parameter explicitly, e.g. Param<IEnumerable<int>>._1
You can arrange boolean members implicitly – instead of writing “
&& me.Bool == true”, simply write “&& me.Bool”; also, instead of writing “&& me.Bool == false”, write “&& !me.Bool”.
You cannot set expectations on arrangements – only the return values. If you need to set an expectation, then make an additional
arrangement on the created mock for both its return value and any expectations using the Mock.Arrange() syntax.
If we have the following system under test:
We can make stub for it, like this:
However, if we want to add expectations to Open(), we cannot with the above syntax.
We have to use the old syntax. We also can’t define the return value with the new syntax and then the expectations with
Mock.Arrange(). We have to use the old one for the entire arrangement:
At any time, for any mock, you can add additional arrangements using the new syntax by calling
Mock.ArrangeLike(someMock, me => ...);