c# - 如何模拟 LINQ to Entities 助手,例如 'SqlFunctions.StringConvert()'

标签 c# unit-testing entity-framework-4 mocking moq

我正在使用 EF 4 并尝试使用 Moq 对以下行进行单元测试:

var convertError = models
             .Where(x => SqlFunctions.StringConvert((decimal?) (x.convert ?? 0)) == "0")
             .Any();

如果 SqlFunctions.StringConvert() 检测到上下文被模拟,它似乎会抛出异常。

它给出一个错误提示:

This function can only be invoked from LINQ to Entities

是否可以告诉 SqlFunctions.StringConvert 返回一个模拟对象,这样我就可以摆脱这个错误?

最佳答案

我所做的是提供我自己的 DbFunctions 实现,这样单元测试中的 LINQ To Objects 使用简单的 .NET 实现,而 LINQ To EF 在运行时使用 DbFunctionAttribute 的方式与 System.Data.Entity.DbFunctions 相同.我曾考虑过模拟 DbFunctions,但是嘿,LINQ to Objects 实现很有用并且工作正常。这是一个例子:

public static class DbFunctions
{
    [DbFunction("Edm", "AddMinutes")]
    public static TimeSpan? AddMinutes(TimeSpan? timeValue, int? addValue)
    {
        return timeValue == null ? (TimeSpan?)null : timeValue.Value.Add(new TimeSpan(0, addValue.Value, 0));
    }
}

关于c# - 如何模拟 LINQ to Entities 助手,例如 'SqlFunctions.StringConvert()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14968513/

相关文章:

asp.net - Entity Framework asp.net 应用程序中的 UOW 和存储库

C# Linq to Entities 获取日期范围包含当月日期的记录

c# - ItextSharp 在页面中心添加图像,并在其下方添加文本

c# - 如何使用 C# WPF 打开 chm 文件中的特定页面

c# - 限制C#中的并行线程数

unit-testing - 桌面应用程序和 Web 应用程序之间的区别

java - Spring 依赖项没有被注入(inject)到 BeforeSuite 方法中?

c# - C#未运行派生类函数

c++ - gtest - 确保某个方法之前没有被调用,但可以在某个方法调用之后被调用

c# - nBuilder 测试数据生成器和反射