Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test repository method

I have this method to unit test:

public virtual TEntity Get(int id)
        {
            return _db.Set<TEntity>().Find(id);
        }

Could someone please tell me how to unit test this?

I'm thinking what I need to test is that Find is called with the correct id?

First I was trying to mock the context _db using Moq. Set isn't virtual though so can't use Verify.

Could someone please suggest an alternative method of testing this?

like image 669
AnonyMouse Avatar asked Jan 18 '23 22:01

AnonyMouse


1 Answers

Repository implementation is usually full of calls to ORM API. There is nothing to unit test here. You should write an integration test instead. Use in memory database like SQLite. Read this or this. This way you will cover your mappings, criteria, HQL etc. I know that you are using EF but I think that principle is the same as NHibernate.

Regarding mocking _db. There is a very good guideline: Don't mock types you don't own.

like image 65
Dmitry Avatar answered Jan 29 '23 03:01

Dmitry