2

I am wondering if I can use FakeItEasy with EF Core? I need to write some unit tests around CRUD operations. Can someone provide some insight into whether I should use In memory database or FakeItEasy? Any help regarding this will be highly appreciated. Thank you.

Vin
  • 101
  • 1
  • 1
  • 4
  • 1
    Definetely In-Memory database. Or if you want test some relational database features then you can use "in-memory" SQLite. You don't want to mock EntityFramework, because it would be testing your implementation details, where every time you change a query, without changing behaviour, you will need rewrite your tests. – Fabio Oct 19 '18 at 02:13
  • 1
    Possible duplicate of [Mocking Entity Framework Core context](https://stackoverflow.com/questions/47553878/mocking-entity-framework-core-context) – Thomas Levesque Oct 19 '18 at 12:13
  • 1
    Technically, you can mock it (most methods in `DbSet` are virtual), but it's difficult to setup. Use in memory database, as described here: https://stackoverflow.com/a/47554912/98713 – Thomas Levesque Oct 19 '18 at 12:14

1 Answers1

2

You can have a look my MockQueryable package. It supports FakeItEasy.

Simple example:

 //1 - create a List<T> with test items
 var users = new List<UserEntity>()
 {
   new UserEntity{LastName = "ExistLastName", DateOfBirth = DateTime.Parse("01/20/2012")},
   ...
 };
 
 //2 - build mock by extension
 var mock = users.AsQueryable().BuildMock();
 
 //3 - setup the mock as Queryable for FakeItEasy
 A.CallTo(() => userRepository.GetQueryable()).Returns(mock);

Here you can find more examples of usage MockQueryable + FakeItEasy

R.Titov
  • 3,115
  • 31
  • 35