c# - How should I unit test a repository method implemented with Entity Framework? -


i have method in repository layer:

public ienumerable<user> getactiveusers() {     return dbcontext.users            .where(u => u.isactive)            .orderby(u => u.name)            .tolist(); } 

should unit test method mocking dbcontext or should test actual database?

i know stops being "unit" test when use actual database, don't see value in mocking dbcontext test repository methods thin in logic , calls ef's method directly.

and if have use actual database, there standard strategy populate test data in database tests run independently , not alter state in database?

probably not want hear, don't want mock dbcontext. know it's been done time , in ef6 it's been made easier before. there yet more interfaces , virtual methods available implement mock objects. technically it's not hard.

it's behavior matters.

even in small example there possible catch. mock dbset case-sensitive sorting. connected dbset receive sorted data database , many database collations happen case-insensitive. unit test could produce different results integration test, in seemingly insignificant case.

the differences between in-memory , connected linq overwhelming. personally, integration tests involves linq entities query. it's easy create mock object graph different if ef have built it. in service methods compose pretty complex queries, maybe involving includes, maybe deliberately omitting null guards, knowing statement translated sql, maybe involving lazy loading or relying on relationship fixup. have aware of entity states, context lifespans, validation kicks in when saving changes, concurrency ... don't believe green tests when it's mocked.

of course there's enough business logic left test pure unit test. once can make assumption correct objects available (because test separately in integration tests) can mock them , unit test behavior in-memory.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -