Returns
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:
You may additionally want to check theCreate Mocks By Example article.
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.
Refer to the Matchers help topic 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.
In this example, Echo
is called on a new Foo
instance, instead of a mocked one. However, the arrangement is applied.