Mocking LINQ Queries
This article provides practical examples that demonstrate how to mock LINQ queries with Telerik® JustMock and custom select.
This feature is available only in the commercial version of Telerik JustMock. Refer to this topic to learn more about the differences between the commercial and free versions of Telerik JustMock.
If you need a complete Visual Studio project that demonstrates how to mock LINQ queries, refer to our demo. The default installation directory is C:\Program Files (x86)\Progress\Telerik JustMock\Examples.
Prerequisites
In the further examples, we will use the following method and sample classes to test:
Important
To mock LINQ queries you first need to go to elevated mode by enabling TelerikJustMock from the menu. Learn how to do that in the How to Enable/Disable Telerik JustMock topic.
Asserting Custom Select Query
In the following example, we mock simple.Products
to return a custom collection. After that, a LINQ query is executed against the collection to obtain a specifically desired value:
simple.Products
will return the collection defined by GetProductLists
, the Product
with UnitsInStock
property set to 50
has the ProductID
set to 2
, and therefore the assertion will pass.
Asserting Projection
Let's extend the previous example. Here, in our LINQ query, we don't get directly the values we need, but construct a new object of type Product
and verify the ProductID
property.
There is only one Product
in the collection returned from GetProductLists()
with UnitsInStock
= 50
and its ProductID
property yields 2
.
Asserting Queries with Join Operator
Furthermore, you can use Join operations to create associations between sequences that are not explicitly modeled in the data sources. For example, you can perform a join to find the CategoryName
of each product.
Asserting Enumerable Source
With JustMock, you can also mock an enumerable source. Let's add the following method and a class:
We arrange dataContext.Products
to return the collection defined in the GetFakeProducts
method. Yet it implements IQueryable
interface, we are allowed to use it in our assertion. Here we verify it contains 3
elements.
Asserting When Conditional Expression Is Passed in as a Parameter
You can also mock parameters when using the LINQ expressions. Let's walk through an example demonstrating how to mock the behavior of the ==
expression:
In this example, we first define that the product collection must be a specific list of products. We then use LINQ to select a specific instance from the simple.Products
collection. For that instance, we want to mock the call to the GetId()
method in order to return a different id. Finally, we retrieve the target product and verify that the returned id and the expected id are the same.