字节[]在LINQ到SQL,并在单元测试,使用比较嘲讽 [英] Comparing byte[] in LINQ-to-SQL and in a unit test that uses mocking
问题描述
我有以下方式:
User IDataContext.AuthenticateUser(string userName, string password)
{
byte[] hash = PasswordHasher.HashPassword(userName, password);
var query =
from e in mContext.GetTable<User>()
where e.Email == userName && e.Password == hash
select e;
return query.FirstOrDefault();
}
在 mContext
是一个 System.Data.Linq.DataContext
一切都很正常。然而,当 mContext
是我联合测试过程中在内存中的模拟, e.Password
之间的比较和散
总是返回假
。
When mContext
is a System.Data.Linq.DataContext
everything works great. However, when mContext
is an in-memory mock during my uniting testing, the comparison between e.Password
and hash
always returns false
.
如果我重写这个比较,因为 e.Password.SequenceEqual(散)
,那么我的单元测试通过,但我得到一个异常时,我说的LinqToSql。 (System.NotSupportedException:查询经营者SequenceEqual'不支持)
If I rewrite this comparison as e.Password.SequenceEqual(hash)
, then my unit tests will pass, but I get an exception when I'm talking to LinqToSql. (System.NotSupportedException: The query operator 'SequenceEqual' is not supported.)
有没有办法,我可以写这个查询,将满足我的单元测试用的方式 - 内存模拟,以及与LinqToSql生产的组成部分?
Is there a way that I can write this query that will satisfy my unit tests with an in-memory mock, as well as the production component with LinqToSql?
推荐答案
这是一个有趣的。我想不出拦截等于没有打破一切的一种便捷方式,但:是用户名独特之处?你可以只是包含在LINQ的用户名条件,然后检查常规C#哈希值。在数据方面传送有传递给它在和提取出来,特别是如果我们优化了成功的情况下(在这种情况下,这<青霉>减少的在IO要求)。
That's an interesting one. I can't think of a convenient way of intercepting the equals without breaking everything, but: are the user-names unique? You could just include the username condition in the LINQ, then check the hash in regular c#. In terms of data transferred there is little difference between passing it in and fetching it out, especially if we optimise for the success case (in which case this reduces the IO requirements).
请注意:返回相同的结果为未发现和不匹配,如果你做到这一点。
Note: return the same result for "not found" and "not a match" if you do this.
由于字节[。 ]比较不再由LINQ到SQL,它应该工作在现在的模拟罚款取决于特殊处理。
Because the byte[] compare no longer depends on special treatment by LINQ-to-SQL, it should work fine in your mock now.
var user = (by name).SingleOrDefault();
if(user==null) #fail
bool hashMatch = /* compare array */
if (!hashMatch) #fail
return user;
这篇关于字节[]在LINQ到SQL,并在单元测试,使用比较嘲讽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!