Create and Arrange Mocks at the Same Time
The built-in feature for creating mocks by specific arrangement 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 to arrange their behavior at the same time through the Mock.CreateLike method.
Using Mock.CreateLike
Let's take the following system under test for example:
Sample Setup
For simple tests with few arrangements, this provides only marginal benefit. The real benefit comes with complex tests with multiple arrangements, like the one demonstrated in Example 1.
Example 1: Create and Arrange with Mock.Create and Mock.Arrange
To first explain the functionality in more details, let’s see Example 2 which shows how you can rewrite the above test using the capabilities provided by Mock.CreateLike
.
Example 2: Using Mock.CreateLike
The API is even more powerful and you can define all the arrangements from the above test in a single line:
Example 3: Using Mock.CreateLike to create and arrange memebers on a single line
The syntax reflects the hierarchical structure of the complex arrangement much better and makes trivial arrangements (like for the values of properties) easy.
Using Matchers with Mock.CreateLike
When creating mocks with Mock.CreateLike
, you can also use argument matchers in method arguments, just like in regular Mock.Arrange()
expressions.
Sample setup
Example 4: Mock.CreateLike with argument matchers
You can even refer to the arguments of the method when specifying its return value, like demonstrated in Example 4. In this example, the Param._1
and Param._2
bits are placeholders for the actual arguments passed to the arranged method. In other words, the arrangement means that Object.Equals
will be called instead of cmp.Equals
, and the parameters of cmp.Equals
will be transferred as parameters of Object.Equals
.
When you need to use argument matchers and the type you need is not present in the Arg.Any~ properties, you can also use a custom type by matching it using the
Arg.IsAny<T>()
method.
Using CreateLike With Additional Expectation Clauses
With Mock.CreateLike
you can arrange return values. If you would like to set additional expectation clauses like DoNothing
, DoInstead
, Occurs
, etc., you should use Mock.Arrange
. To show how you can do that, let’s use the setup shown below.
Sample setup
For simple cases, you can create a test like the one in Example 5.
Example 5: Arrange return values
However, if you need to add expectations to Open()
, you cannot with the above syntax. You should use Mock.Arrange
to add them.
Example 6: Arrange return values and set additional expectations
At any time, for any mock, you can add additional arrangements using
Mock.Arrange
for mock objects created withMock.CreateLike
.