Unit testing LINQ to SQL repositories can be very challenging. Unit testing such requires faking hard to mock classes and requires simulation to return your custom data for a particular LINQ statement. In this post, i will show how you can mock your LINQ repositories easily without much digging in.
As, i was goggling [my start page is bing, its a matter of time when i will be bing-ing :-)] around, found a nice post by Ronnie Holm, where he shows how to unit test a LINQ to SQL repository. I will follow his trail and use some of the codes from his post. Therefore, first of all we have an employee class:
Secondly, we have an LINQ DataContext implementation that has the Table<Employee> which we are going to mock with our expected collection.
Next, we have a repository that contains the LINQ query which is going to be queried on our fake collection that will let us validate the LINQ query in subsequent calls.
Here, i have removed the ToList() from Ronnie’s code. In ideal case, people may not be having ToList() call into their LINQ query all the time. Secondly, i added the a way to pass our faked DataContext to the repository class. As there should be a minimal dependency to keep the code structure immutable and i think its not a best practice to mock a call for future instances, where it does not have any tie with current code flow.
Finally, its all about mocking , and the steps are:
Therefore, it becomes:
Here, you might like to ensure that your collection is set right, so it is possible to do
That’s it for today. Again special and indirect thanks goes to Ronnie, because i used his code and to him for mentioning JustMock in his post.
Link to the sample project : LINQToSql001.zip
Copyright © 2017, Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
Progress, Telerik, and certain product names used herein are trademarks or registered trademarks of Progress Software Corporation and/or one of its subsidiaries or affiliates in the U.S. and/or other countries. See Trademarks or appropriate markings.