本文介绍了如何嘲笑LINQ到实体佣工如“SqlFunctions.StringConvert()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用EF 4,并试图单元测试使用Moq的后续行:

I am using EF 4 and is trying to unit test the follow line using Moq:

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

和它看起来像 SqlFunctions.StringConvert()如果检测到上下文嘲笑将抛出。

and it seems like SqlFunctions.StringConvert() will throw if it detects the context is mocked.

它给出了一个错误说:

这功能只能通过调用LINQ到实体

是否可以告诉 SqlFunctions.StringConvert 返回?模仿对象,所以我可以摆脱这个错误

Is it possible to tell SqlFunctions.StringConvert to return a mock object so I can get rid of this error?

推荐答案

没有它,因为函数的实现看起来是不可能的:

No it is not possible because the function's implementation looks like:

[EdmFunction("SqlServer", "STR")]
public static string StringConvert(decimal? number, int? length)
{
    throw EntityUtil.NotSupported(Strings.ELinq_EdmFunctionDirectCall);
}

您不能使用起订量伪造此功能。你需要更强大的模拟框架,让您取代静态的函数调用 - 可能是微软正版正货,TypeMock隔离或JustMock

You cannot use Moq to fake this function. You need more powerful mocking framework which will allow you replacing static function call - probably Microsoft Fakes, TypeMock Isolator or JustMock.

或者你需要考虑你的测试方法,因为嘲讽上下文是错误的想法。而应该有这样的事情:

Or you need to think about your testing approach because mocking the context is the wrong idea. You should instead have something like:

var convertError = myQueryProvider.ConvertQuery(x.convert); 



其中, queryProvider 将是您mockable类型隐藏您的查询。查询是数据库相关的逻辑,它应该对真正的数据库进行测试。在你的查询代码是你的应用程序逻辑,它应该是单元测试 - 最佳的解决方案,以测试它们都能够正确只是通过一些接口(查询供应商在这种情况下,但人们往往有一个完整的特定存储库去)将它们分开。这一原则来自于关注点分离 - 查询执行是分开的关注,因此被放置到它自己的方法是分别进行测试。

Where queryProvider will be your mockable type hiding your query. Query is database related logic and it should be tested against the real database. Code around your query is your application logic and it should be unit tested - the best solution to test them both correctly is simply to separate them through some interface (query provider in this case but people often go with a full specific repository). This principle comes from separation of concerns - query execution is separate concern so it is placed into its own method which is tested separately.

这篇关于如何嘲笑LINQ到实体佣工如“SqlFunctions.StringConvert()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 11:45