简体   繁体   English

如何对以Lambda表达式为参数的存储库方法进行单元测试

[英]How to Unit Test Repository Method That Takes Lambda Expression as A Parameter

I have a repository method as follows: 我有一个存储库方法,如下所示:

 public ICollection<TEntity> Find(Expression<Func<TEntity, bool>> where)
 {
        return Set.Where(where).ToList();
 }

Set is an EntityFramework DbSet<TEntity> Set是一个EntityFramework DbSet<TEntity>

What is the best approach to unit test this method? 对这种方法进行单元测试的最佳方法是什么? I can mock the DbSet<TEntity> to return some dummy data easily, but I'm not entirely sure of what constitutes a valid or worthwhile test for this method. 我可以模拟DbSet<TEntity>轻松返回一些虚拟数据,但是我不完全确定什么构成此方法的有效或有价值的测试。

For example, I can test the return type is correct and that an empty collection is returned for a predicate that is clearly never going to be satisfied, but what other tests should I be running? 例如,我可以测试返回类型是否正确,并且返回一个谓词的空集合,而该谓词显然永远不会满足,但是我还应该运行其他哪些测试?

Should I just write a test that passes an expression that is always true to test true conditions and another test that passes an expression that is always false to test false conditions? 我是否应该编写一个测试,该测试通过一个始终为true的表达式以测试真实条件,而另一个测试则通过一个始终为false的表达式以测试错误条件?

When you mock the Set there´s nothing more in the method which effectivly can be tested. 当你嘲笑的Set没有其它仪器更在其用途不同可以进行测试的方法。 The method then consists only of a mock and nothing more. 然后,该方法仅包含一个模拟,仅此而已。 If Set is just a mock a call to Where will also return any dummy data according to how you set your mock. 如果Set只是一个模拟,则对Where的调用也将根据您设置模拟的方式返回任何虚拟数据。 So you´re actually testing that your mock was mocked the way you want instead of your method to do the right things with the data retrieved from that mock. 因此,您实际上是在测试是否以所需的方式对模拟进行了模拟,而不是对从模拟中检索的数据执行正确操作的方法进行了测试。 Since what you do with this data is trivial (just calling ToList on it) there´s no need to do any testing here. 由于处理这些数据很简单(只需对其调用ToList ,因此无需在此处进行任何测试。

However you should consider that the actual Expression was built correctly, but you won´t do this within the test for that method but within the test for the calling code. 但是,您应该考虑到实际的Expression是正确构建的,但是您不会在针对该方法的测试中而是针对调用代码的测试中进行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM