简体   繁体   中英

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>

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.

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?

When you mock the Set there´s nothing more in the method which effectivly can be tested. 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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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