The Returns method is used with non void calls to ignore the actual call and return a custom value.
This topic goes through a number of scenarios where the Returns method is useful.
For them, we will be using the following interface:
Further, you can also check Create Mocks By Example.
Assert Property Get Call
With Returns method you can change the return value from a property get call.
In this example we arrange the Bar property get to return 10 when called. By acting with actual = foo.Bar;
we assign 10 to actual, as foo.Bar will result in 10. Finally, a verification is asserted.
Assert Method Call with Matcher
A common case is to mock a method call to return a custom value in conjunction with a matcher.
Here we use an Arg.IsAny matcher for the call to match calls to foo.Echo with any int argument.
In the Returns method, instead of using a simple int value,
we use a function to return the passed value incremented with 1.
You may also use a more complicated matcher. For example, you can make arrangement for passing
exactly 10 to Echo method. With the following line of code we return exactly what has been passed:
The following example mocks the Execute method so that it returns its second argument.
We use lambda expression in the Returns body to select the desired argument. After we have arranged
we act by calling foo.Execute(100, 10) and verify that it has returned actually what we expect, namely 10.
Additionally, we verify that a call with any int as first argument and exactly 10 as second has been made.
Follows an example, showing mocking method in F#:
member this.ShouldMockMethodCallsWithReturn() =
let monkey = Mock.Create<IMonkey>()
Mock.Arrange(monkey, fun ignore -> monkey.Echo()).Returns(10).MustBeCalled()
let result = monkey.Echo()
We arrange the Echo method to return 10 and expect that it will actually be called in our test.
After acting by calling the method, we verify the arrangement.
Furthermore, you can assert that result has the value of 10.
Refer to Matchers for more information about using matchers.
Executing Mocked Method In Same Test Method
Assume we have the following class:
JustMock supports executing mocked method in same test method without necessarily passing the type as an argument.
Here, in this example, Echo is called on a new Foo instance, instead of a mocked one. However, the arrangement is applied.