Generics
Telerik® JustMock allows you to mock generic classes/interfaces/methods in the same way as you do it for non-generic ones.
In the next examples we will use the following three sample classes to test:
Distinguish Generic Method Calls with Different Arguments
Set up a call to a generic method and distinguish calls depending on the argument type.
We arrange the Get<T>
method to return different values when called with either int
or string
argument.
The syntax for mocking generic method is:
Mock.Arrange(() => <class_name>.<method_name><type>())...;
After that you act in the same way as you do it for non-generic methods except that you specify argument type. That is:
int actualCallWithInt = foo.Get<int>();
Mock a Generic Method with Out Argument
Set up a call to a generic method with out argument.
In the arrange statement we use the out
keyword and pass the already initialized variable. It is of type string
as we specified the type argument of the Submit
method to string
. Thus, we arrange that a call to Submit
should set the out argument to "ping"
.
Mock a Generic Class
Set up a call to a method of a generic class.
In this example we mock the generic class FooGeneric<int>
. The only difference from mocking non-generic classes is specifying the argument type in the Mock.Create
call. After that you act in the same manner when calling non-generic methods.
Here is another example for mocking the Get
method:
In this example we specify that the method accepts only two specific arguments and will return 10
.
You can also mock void methods of generic classes. In the next example we mock the Execute
method by replacing the implementation so that it sets a boolean value to true.
Mock Generic Method in Non-generic Class
Generic methods in non-generic class can also be mocked.
Here is an example:
First, we arrange that the Get
method will be called only with int
argument 1
and return int
value 10
. After that, we verify.