Unit testing is the base level of the testing pyramid and thus a vital cornerstone of effective software development. In order to effectively unit test your code you should make use of SOLID design principles and mocking frameworks. That said, it isn’t always easy to accomplish such as mocking IQueryable Extensions.

I recently ran into a case where I was trying to strangle some code out of a monolith. I added an interface around an OData client to expose a single IQueryable property for now. As part of this dev cycle I’m creating a new caching layer around that interface, putting it into it’s own Git repository, and then publishing as a reusable Nuget package. We plan on adding more data type caches to this library and want to reuse it across multiple internal projects. The majority of our tests are MSTest with Moq so that’s the pattern I need to follow.

Properly unit testing your code can help make you a better developer just like it does for me.

Scenario

Consider an interface something along these lines:

public interface IDataClient 
{
	IQueryable<MyModel> MyModels { get; }
}

In this particular use-case I have a cache specifically built around MyModel. That cache has IDataClient as a direct dependency. My cache has a few different methods and I need to test each one of them. In order to have a complete unit test I need to verify that if an item is already in the cache it doesn’t attempt to load it again. Hopefully I’ve now set enough of the stage for the problem I faced.

#.net #.net core #asp.net #mocking #unit testing

Mocking IQueryable Extensions with Moq
2.80 GEEK