Unit testing LINQ queries can be really challenging. This requires a deep knowledge of how LINQ queries work and how they filter results based on predicate values. While I am adopting test first development approach, it is most likely that I want to verify the behavior of a query for correctness. In this post, I will show how easy it is to mock a LINQ query using JustMock for a given context.
First, let me build up the context with a simple entity class for Employee that has two properties:
Next, I created a dummy context that inherits the LINQ to SQL DataContext class and exposes employees through Table<Employee> that implements IQueryable:
I then created a repository that depends on the above data context and contains only one method GetEmployeesByHireDate:
Now, my goal is to mock the query so that it executes against our fake collection instead of fetching it from disk or database. Note that in the real world, developers will write varying queries, not just one as in this example. This variability makes it difficult (if not impossible) to create a TestFake around the IQueryable Employees table. Using JustMock, I can intercept the data context to return a specific collection against which the query will be executed and verify the correctness of the query based on expected result.
Based on the above context, the repository is mocked in three simple steps:
- Mock the AdventureWorksDataContext class
- Return fake collection for context.Employees
- Act and assert.
In Telerik.JustMock.Helpers namespace there is a method called ReturnsCollection and when used against an IQueryable does the heavy lifting of initializing the expression tree with the specific collection.
This makes the process as simple as asserting against a real entity collection, letting me focus only on the context and eliminating noise.
Finally, I asserted that for a given date the GetEmployeesByHireDate method returns the correct employee(s) from my fake collection, proving the correctness of my query.
In order to learn more on mocking LINQ queries, I would also urge you to check the JustMock online documentation for further information.
Often developers find it challenging to unit test LINQ queries. Without JustMock, digging down the expression tree to discover entry point extensions can be considerable time and/or effort to cover a simple scenario. ReturnsCollection delivers simplicity in mocking LINQ queries and makes it fun.