Moq and entity

So this week while trying to implement a repository pattern within a MVC Web API project I found myself writing unit tests to verify that the response is what we would expect.  As part of this, the entity query was using the DbFunctions.AddDays method.  When you mock the backing DBSet collections, the code does not know what to do with these DbFunctions and will throw an error. After a LOT of googling and research, below is the solution I came up with…

//switch between entity filter and linq filter (needed for unit testing)
if (AppDomain.CurrentDomain.GetAssemblies().Any(t => t.GetName().Name == "Microsoft.VisualStudio.QualityTools.UnitTestFramework")) {
binderQuery = binderQuery.Where(t => DateTime.UtcNow < t.CreatedDateTimeUTC.AddDays(t.ExpirationInDays));
else {
binderQuery = binderQuery.Where(t => DateTime.UtcNow < System.Data.Entity.DbFunctions.AddDays(t.CreatedDateTimeUTC, t.ExpirationInDays));
binderQuery = binderQuery.Where(t => System.Data.Entity.DbFunctions.AddDays(t.CreatedDateTimeUTC, t.ExpirationInDays) > DateTime.UtcNow);

By doing this, when the code gets compiled in release mode, it will not include the logic for looking at the assemblies to bypass the DbFunctions call. Therefore, this work around should not affect production level code from a performance perspective.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s