0

I started writing tests for a (webapi) application in .net core using ef core. The repositories I want to test look like this:

   public class MyRepository : IMyRepository
   {
   private readonly IDbContext Db;
   public MyReporitory(IDbContext db) 
      {
         Db = db;
      }
   /// Methods to access the Database
      public List<MyType> Get() {
         return Db.Set<Type>();
      }

In my test I now try to mock the DBContext:

 var dbContextMock = new Mock<IDBContext>();
 var classToBeTested = new MyRepository(dbContextMock)
 var result = classToBeTested.Get() (or any other method in my repository);
 Assert.That(result, Is.TypeOf<MyType>)

When I run the test I get a null exception since the returned result is null (and I didnt tell the mock how to return data?) How would I add data to the mocked DbContext so the Get() can get it?

Myko
  • 59
  • 1
  • 11
  • Does this answer your question? [Mocking EF core dbcontext and dbset](https://stackoverflow.com/questions/54219742/mocking-ef-core-dbcontext-and-dbset) Don't just look at the accepted answers which involves in memory db (which I suggest using instead)... The second highest answer shows how to setup mocks if you really need to go that route – pinkfloydx33 Jun 02 '20 at 09:02

1 Answers1

0

Use moq setup to return data. If I am correct you have created an Set method in your interface. Just mock that method

If your set method returns an DbSet type then you can mock it with this bit of code

        var mockDbSet = new Mock<DbSet<TestClass>>();
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.Provider).Returns(data.Provider);
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.Expression).Returns(data.Expression);
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.ElementType).Returns(data.ElementType);
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator);

data is of an type IQueryable

Strike08
  • 267
  • 1
  • 2
  • 17