EntityFunctions.TruncateTime and unit tests

会有一股神秘感。 提交于 2019-12-17 22:57:18

问题


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?


回答1:


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...

context.MyEntities.Where(e => MyBoolFunction(e)).ToList()

or

context.MyEntities.Select(e => new MyEntity { Name = e.Name }).ToList()

...will work fine in your test but not with LINQ to Entities in your application.

A query like...

context.MyEntities.Where(e => e.Name == "abc").ToList()

...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 Where expression:

public interface IEntityExpressions
{
    Expression<Func<MyEntity, bool>> GetSearchByDateExpression(DateTime date);
    // maybe more expressions which use EntityFunctions or SqlFunctions
}

Create an implementation for your application...

public class EntityExpressions : IEntityExpressions
{
    public Expression<Func<MyEntity, bool>>
        GetSearchByDateExpression(DateTime date)
    {
       return e => EntityFunctions.TruncateTime(e.Date) == date;
       // Expression for LINQ to Entities, does not work with LINQ to Objects
    }
}

...and a second implementation in your Unit test project:

public class FakeEntityExpressions : IEntityExpressions
{
    public Expression<Func<MyEntity, bool>>
        GetSearchByDateExpression(DateTime date)
    {
        return e => e.Date.Date == date;
       // Expression for LINQ to Objects, does not work with LINQ to Entities
    }
}

In your class where you are using the query create a private member of this interface and two constructors:

public class MyClass
{
    private readonly IEntityExpressions _entityExpressions;

    public MyClass()
    {
        _entityExpressions = new EntityExpressions(); // "poor man's IOC"
    }

    public MyClass(IEntityExpressions entityExpressions)
    {
        _entityExpressions = entityExpressions;
    }

    // just an example, I don't know how exactly the context of your query is
    public IQueryable<MyEntity> BuildQuery(IQueryable<MyEntity> query,
        SearchOptions searchOptions)
    {
        if (searchOptions.Date.HasValue)
            query = query.Where(_entityExpressions.GetSearchByDateExpression(
                searchOptions.Date));
        return query;
    }
}

Use the first (default) constructor in your application:

var myClass = new MyClass();
var searchOptions = new SearchOptions { Date = DateTime.Now.Date };

var query = myClass.BuildQuery(context.MyEntities, searchOptions);

var result = query.ToList(); // this is LINQ to Entities, queries database

Use the second constructor with FakeEntityExpressions in your unit test:

IEntityExpressions entityExpressions = new FakeEntityExpressions();
var myClass = new MyClass(entityExpressions);
var searchOptions = new SearchOptions { Date = DateTime.Now.Date };
var fakeList = new List<MyEntity> { new MyEntity { ... }, ... };

var query = myClass.BuildQuery(fakeList.AsQueryable(), searchOptions);

var result = query.ToList(); // this is LINQ to Objects, queries in memory

If you are using a dependency injection container you could leverage it by injecting the appropriate implementation if IEntityExpressions into the constructor and don't need the default constructor.

I've tested the example code above and it worked.




回答2:


You can define a new static function (you can have it as an extension method if you want):

    [EdmFunction("Edm", "TruncateTime")]
    public static DateTime? TruncateTime(DateTime? date)
    {
        return date.HasValue ? date.Value.Date : (DateTime?)null;
    }

Then you can then use that function in LINQ to Entities and LINQ to Objects and it will work. However, that method means that you would have to replace calls to EntityFunctions with calls to your new class.

Another, better (but more involved) option would be to use an expression visitor, and write a custom provider for your in-memory DbSets to replace the calls to EntityFunctions with calls to in-memory implementations.




回答3:


As outlined in my answer to How to Unit Test GetNewValues() which contains EntityFunctions.AddDays function, you can use a query expression visitor to replace calls to EntityFunctions functions with your own, LINQ To Objects compatible implementations.

The implementation would look like:

using System;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;

static class EntityFunctionsFake
{
    public static DateTime? TruncateTime(DateTime? original)
    {
        if (!original.HasValue) return null;
        return original.Value.Date;
    }
}
public class EntityFunctionsFakerVisitor : ExpressionVisitor
{
    protected override Expression VisitMethodCall(MethodCallExpression node)
    {
        if (node.Method.DeclaringType == typeof(EntityFunctions))
        {
            var visitedArguments = Visit(node.Arguments).ToArray();
            return Expression.Call(typeof(EntityFunctionsFake), node.Method.Name, node.Method.GetGenericArguments(), visitedArguments);
        }

        return base.VisitMethodCall(node);
    }
}
class VisitedQueryProvider<TVisitor> : IQueryProvider
    where TVisitor : ExpressionVisitor, new()
{
    private readonly IQueryProvider _underlyingQueryProvider;
    public VisitedQueryProvider(IQueryProvider underlyingQueryProvider)
    {
        if (underlyingQueryProvider == null) throw new ArgumentNullException();
        _underlyingQueryProvider = underlyingQueryProvider;
    }

    private static Expression Visit(Expression expression)
    {
        return new TVisitor().Visit(expression);
    }

    public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
    {
        return new VisitedQueryable<TElement, TVisitor>(_underlyingQueryProvider.CreateQuery<TElement>(Visit(expression)));
    }

    public IQueryable CreateQuery(Expression expression)
    {
        var sourceQueryable = _underlyingQueryProvider.CreateQuery(Visit(expression));
        var visitedQueryableType = typeof(VisitedQueryable<,>).MakeGenericType(
            sourceQueryable.ElementType,
            typeof(TVisitor)
            );

        return (IQueryable)Activator.CreateInstance(visitedQueryableType, sourceQueryable);
    }

    public TResult Execute<TResult>(Expression expression)
    {
        return _underlyingQueryProvider.Execute<TResult>(Visit(expression));
    }

    public object Execute(Expression expression)
    {
        return _underlyingQueryProvider.Execute(Visit(expression));
    }
}
public class VisitedQueryable<T, TExpressionVisitor> : IQueryable<T>
    where TExpressionVisitor : ExpressionVisitor, new()
{
    private readonly IQueryable<T> _underlyingQuery;
    private readonly VisitedQueryProvider<TExpressionVisitor> _queryProviderWrapper;
    public VisitedQueryable(IQueryable<T> underlyingQuery)
    {
        _underlyingQuery = underlyingQuery;
        _queryProviderWrapper = new VisitedQueryProvider<TExpressionVisitor>(underlyingQuery.Provider);
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _underlyingQuery.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public Expression Expression
    {
        get { return _underlyingQuery.Expression; }
    }

    public Type ElementType
    {
        get { return _underlyingQuery.ElementType; }
    }

    public IQueryProvider Provider
    {
        get { return _queryProviderWrapper; }
    }
}

And here is a usage sample with TruncateTime:

var linq2ObjectsSource = new List<DateTime?>() { null }.AsQueryable();
var visitedSource = new VisitedQueryable<DateTime?, EntityFunctionsFakerVisitor>(linq2ObjectsSource);
// If you do not use a lambda expression on the following line,
// The LINQ To Objects implementation is used. I have not found a way around it.
var visitedQuery = visitedSource.Select(dt => EntityFunctions.TruncateTime(dt));
var results = visitedQuery.ToList();
Assert.AreEqual(1, results.Count);
Assert.AreEqual(null, results[0]);



回答4:


Although I like the answer given by Smaula using the EntityExpressions class, I think it does a bit too much. Basically, it throws the entire entity at the method, does the compare, and returns a bool.

In my case, I needed this EntityFunctions.TruncateTime() to do a group by, so I had no date to compare to, or bool to return, I just wanted to get the right implementation to get the date part. So I wrote:

private static Expression<Func<DateTime?>> GetSupportedDatepartMethod(DateTime date, bool isLinqToEntities)
    {
        if (isLinqToEntities)
        {
            // Normal context
            return () => EntityFunctions.TruncateTime(date);
        }
        else
        {
            // Test context
            return () => date.Date;
        }
    } 

In my case, I did not need the interface with the two seperate implementations, but that should work just the same.

I wanted to share this, because it does the smallest thing possible. It only selects the right method to get the date part.




回答5:


I realize this is an old thread but wanted to post an answer anyways.

The following solution is done using Shims

I am not sure what versions (2013, 2012, 2010) and also flavors (express, pro, premium, ultimate) combinations of Visual Studio allow you to use Shims so it might be that this is not available to everyone.

Here is the code the OP posted

// some method that returns some testable result
public object ExecuteSomething(SearchOptions searchOptions)
{
   // some other preceding code 

    if (searchOptions.Date.HasValue)
        query = query.Where(c => 
            EntityFunctions.TruncateTime(c.Date) == searchOptions.Date);

   // some other stuff and then return some result
}

The following would be located in some unit test project and some unit test file. Here is the unit test that would use Shims.

// Here is the test method
public void ExecuteSomethingTest()
{
    // arrange
    var myClassInstance = new SomeClass();
    var searchOptions = new SearchOptions();

    using (ShimsContext.Create())
    {
        System.Data.Objects.Fakes.ShimEntityFunctions.TruncateTimeNullableOfDateTime = (dtToTruncate) 
            => dtToTruncate.HasValue ? (DateTime?)dtToTruncate.Value.Date : null;

        // act
        var result = myClassInstance.ExecuteSomething(searchOptions);
        // assert
        Assert.AreEqual(something,result);
     }
}

I believe this is probably the cleanest and most non-intrusive way to test code that makes use of EntityFunctions without generating that NotSupportedException.




回答6:


You can also check it in the following way:

var dayStart = searchOptions.Date.Date;
var dayEnd = searchOptions.Date.Date.AddDays(1);

if (searchOptions.Date.HasValue)
    query = query.Where(c => 
        c.Date >= dayStart &&
        c.Date < dayEnd);


来源:https://stackoverflow.com/questions/9585203/entityfunctions-truncatetime-and-unit-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!