Unit testing Linq 2 Sql lazy properties

Suppose I have a Customers table and an Orders table with a one-to-many relationship (one customer can have multiple orders). If I have code that I wish to unit test that accesses specific customer orders via lazy loading (e.g. call to customer.Orders) like I mosh / stub call so it doesn't end up in the database

Edit:

To be clearer, let's use a more specific example. Let's say I want to return all orders for a specific customer. I could write it like this using Linq 2 Sql's autogenerated lazy load properties provide:

Customer customer = customerRepository.GetCustomerById(customerId);

return customer.Orders;

      

Unit testing is a little tricky, however. I can mock the call to GetCustomerById, but I cannot (as far as I can tell) send a call to orders. The only way I can think of a unit test is to either a) connect to the database (which will slow down my tests and be brittle) or b) not use the lazy-load properties.

Without using lazy-load properties, I would probably rewrite it as:

return orderRepository.GetOrdersByCustomerId(customerId);

      

This definitely works, but it's awkward to completely ignore the lazy load properties just for unit testing.

+2


source to share


1 answer


As a general answer to your question, you muffle this call the same way you muffle anything else.

I am assuming that the code you want to unit test is the consumer of your data access component as this is the most common scenario. You can only stub data access if you are programming against the interface. This means that you have to hide the L2S implementation details behind the interface so that the consuming code has no idea what implementation it is currently consuming.



The corruption is that lazy loading is an implementation detail that you don't need to worry about when unit testing, because a unit test shouldn't use L2S at all.

When deleting a data access layer, the call is customers.Orders

usually a call to the in-memory Stub property.

+2


source







All Articles