I’m using System.Data.Objects.EntityFunctions.TruncateTime method to get date part of a datetime in my query:
if (searchOptions.Date.HasValue)
query = query.Where(c =>
EntityFunctions.TruncateTime(c.Date) == searchOptions.Date);
This method (I believe the same applies to other EntityFunctions methods) cannot be executed outside of LINQ to Entities. Executing this code in a unit test, which effectively is LINQ to objects, causes a NotSupportedException to be thrown:
System.NotSupportedException : This function can only be invoked from
LINQ to Entities.
I’m using a stub for a repository with fake DbSets in my tests.
So how should I unit test my query?
You can’t – if unit testing means that you are using a fake repository in memory and you are therefore using LINQ to Objects. If you test your queries with LINQ to Objects you didn’t test your application but only your fake repository.
Your exception is the less dangerous case as it indicates that you have a red test, but probably actually a working application.
More dangerous is the case the other way around: Having a green test but a crashing application or queries which do not return the same results as your test. Queries like…
or
…will work fine in your test but not with LINQ to Entities in your application.
A query like…
…will potentially return different results with LINQ to Objects than LINQ to Entities.
You can only test this and the query in your question by building integration tests which are using the LINQ to Entities provider of your application and a real database.
Edit
If you still want to write unit tests I think you must fake the query itself or at least expressions in the query. I could imagine that something along the lines of the following code might work:
Create an interface for the
Whereexpression:Create an implementation for your application…
…and a second implementation in your Unit test project:
In your class where you are using the query create a private member of this interface and two constructors:
Use the first (default) constructor in your application:
Use the second constructor with
FakeEntityExpressionsin your unit test:If you are using a dependency injection container you could leverage it by injecting the appropriate implementation if
IEntityExpressionsinto the constructor and don’t need the default constructor.I’ve tested the example code above and it worked.