Extension Methods Mocking
Mocking extension methods is one of the advanced features supported in Telerik® JustMock. In this topic, we will go through some examples that show how easy and straightforward it is to assert expectations related to extension methods in your tests.
This feature is available only in the commercial version of Telerik JustMock. Refer to this topic to learn more about the differences between both the commercial and free versions of Telerik JustMock.
How To Mock Extension Methods?
You can mock any extension method as you would do it with any other instance method. There is no need to add specific setup or use a dedicated API for extension methods. The Mock.Arrange()
method will help you set up the behavior or expectations you need.
To illustrate this in more examples we will use the following code:
Sample setup
When you have to assert some expectations related to extension methods, you can use everything you already know. Let's go through a very simple example.
Example 1: Arrange extension method behavior
Next, we have a more complex sample where the extension method has more arguments.
Example 2: Arrange the behavior of extension method with several parameters
Similarly, we arrange that when the Echo
extension method is called, it should return the sum of its arguments if the second argument is equal to 10.
For more information on dealing with method parameters, check the Matchers help topic.
Assert Occurrences of Extension Methods
Another thing we can assert is the occurrence of the extension methods. Let's start with an example.
Example 3: Arrange extension method occurrence
The sample code arranges that the extension method should never occur as described in the Asserting Occurrence topic. However, we then call the extension method and assert that an exception is thrown.
Mock Interface Extension Method Calls
This section will show that we can easily mock interface extension method calls when needed. In the example, we will use the following classes:
Sample setup
We have the IDataProvider
interface which we extend with the GetScope
extension method. We can now write tests that mock the extension method's execution:
Example 4: Arrange the behavior of extension method on interface
Here we have arranged that the call to the GetScope
method should return a specific mocked instance of the IObjectScope
interface. We act and assert that the correct value is returned.