相关疑难解决方法(0)

如何在单元测试中使用Moq和DbFunction来防止NotSupportedException?

我目前正在尝试对通过实体框架运行的查询运行一些单元测试.查询本身在实时版本上运行没有任何问题,但单元测试总是失败.

我把它缩小到我对DbFunctions.TruncateTime的使用,但我不知道如何通过这种方式来获得单元测试以反映实时服务器上发生的情况.

这是我正在使用的方法:

    public System.Data.DataTable GetLinkedUsers(int parentUserId)
    {
        var today = DateTime.Now.Date;

        var query = from up in DB.par_UserPlacement
                    where up.MentorId == mentorUserId
                        && DbFunctions.TruncateTime(today) >= DbFunctions.TruncateTime(up.StartDate)
                        && DbFunctions.TruncateTime(today) <= DbFunctions.TruncateTime(up.EndDate)
                    select new
                    {
                        up.UserPlacementId,
                        up.Users.UserId,
                        up.Users.FirstName,
                        up.Users.LastName,
                        up.Placements.PlacementId,
                        up.Placements.PlacementName,
                        up.StartDate,
                        up.EndDate,
                    };

        query = query.OrderBy(up => up.EndDate);

        return this.RunQueryToDataTable(query);
    }
Run Code Online (Sandbox Code Playgroud)

如果我注释掉带有DbFunctions的行,则测试全部通过(除了检查只运行给定日期的有效结果的那些).

有没有办法可以提供在这些测试中使用的DbFunctions.TruncateTime的模拟版本?本质上它应该只返回Datetime.Date,但在EF查询中不可用.

编辑:这是使用日期检查失败的测试:

    [TestMethod]
    public void CanOnlyGetCurrentLinkedUsers()
    {
        var up = new List<par_UserPlacement>
        {
            this.UserPlacementFactory(1, 2, 1), // Create a user placement that is current
            this.UserPlacementFactory(1, 3, 2, …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing entity-framework moq

27
推荐指数
2
解决办法
8160
查看次数

标签 统计

c# ×1

entity-framework ×1

moq ×1

unit-testing ×1