单元测试SqlFunction [英] Unit Test SqlFunctions
问题描述
有没有比创建假的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屋!