单元测试SqlFunction [英] Unit Test SqlFunctions

查看:160
本文介绍了单元测试SqlFunction的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储库暴露了IQueryable,一个服务处理特定的查询,这里有一些使用DbFunctions的方法。为了可测试,我创建一个具有静态列表元素的虚假存储库并将其注入到服务中。问题是,由于我的服务查询了一个List并且没有使用数据库,所以我得到错误这个函数只能从LINQ to Entities调用。



有没有比创建假的DbFunctions和QueryProvider更容易的方法来测试?



提前感谢

解决方案

我试图实现dateDiff函数,它适用于我
,但我们应该认为在这种情况下,我们测试不同的函数
,我们正在测试不是真正的行为

 私有类MySqlFunctions 
{
[DbFunction(SqlServer,DATEDIFF)] // EF会使用这个函数
public int? DateDiff(string datePartArg,DateTime startDate,DateTime endDate)
{
var subtract = startDate.Subtract(endDate);
switch(datePartArg)
{
cased:
return(int?)subtract.TotalDays;
cases:
return(int?)subtract.TotalSeconds; //单元测试将使用这个
}
抛出新的NotSupportedException(方法只支持s或d参数);
}
}

然后在linq代码中

  var sqlFunctions = new TpSqlFunctions(); 

var result = matches.Average(s => sqlFunctions.DateDiff(s,s.MatchCreated,s.WaitingStarted);


I have a repository that exposes IQueryable and a service handles specific queries and here a few methods that make use of DbFunctions. In order to be testable, i create a fake repository with static list of elements and inject it into the service. Problem is, since my service queries a List and does not make use of database, i get the error "This function can only be invoked from LINQ to Entities.".

Is there any easier way for testing this than creating a fake DbFunctions and QueryProvider?

Thanks in advance

解决方案

I'm tried to implement dateDiff function, and it's works for me but we should think that in that case we test different functions and we are testing not real behaviour

 private class MySqlFunctions
    {
        [DbFunction("SqlServer", "DATEDIFF")]//EF will use this function
        public int? DateDiff(string datePartArg, DateTime startDate, DateTime endDate)
        {
            var subtract = startDate.Subtract(endDate);
            switch (datePartArg)
            {
                case "d":
                    return (int?)subtract.TotalDays;
                case "s":
                    return (int?)subtract.TotalSeconds; // unit test will use this one
            }
            throw new NotSupportedException("Method supports only s or d param");
        }
    }

Then in linq code

var sqlFunctions = new TpSqlFunctions();

var result = matches.Average(s => sqlFunctions.DateDiff("s", s.MatchCreated, s.WaitingStarted);

这篇关于单元测试SqlFunction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆