EntityFunctions.TruncateTime and unit tests

后端 未结 6 1599
悲&欢浪女
悲&欢浪女 2020-12-14 15:57

I\'m using System.Data.Objects.EntityFunctions.TruncateTime method to get date part of a datetime in my query:

if (searchOptions.Date.HasValue)
         


        
6条回答
  •  生来不讨喜
    2020-12-14 16:42

    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.

提交回复
热议问题