Mocking EF core dbcontext and dbset

前端 未结 4 2056
无人共我
无人共我 2020-12-28 13:29

I am using ASP.NET Core 2.2, EF Core and MOQ. When I run the test I am getting this error:

Message: System.NotSupportedException : Invalid setup on a

4条回答
  •  梦毁少年i
    2020-12-28 14:04

    I see you are using EF core DbContext in your MovieRepository. So instead of using mock, Using EF Core InMemory database will be a great option for you. This will also reduce the complexity.

    Write your GetAllTest() method as follows:

    [Fact]
    public void GetAllTest()
    {
            var options = new DbContextOptionsBuilder()
                .UseInMemoryDatabase(databaseName: "MovieListDatabase")
                .Options;
    
            // Insert seed data into the database using one instance of the context
            using (var context = new MovieDbContext(options))
            {
                context.Movies.Add(new Movie {Id = 1, Title = "Movie 1", YearOfRelease = 2018, Genre = "Action"});
                context.Movies.Add(new Movie {Id = 2, Title = "Movie 2", YearOfRelease = 2018, Genre = "Action"});
                context.Movies.Add(nnew Movie {Id = 3, Title = "Movie 3", YearOfRelease = 2019, Genre = "Action"});
                context.SaveChanges();
            }
    
            // Use a clean instance of the context to run the test
            using (var context = new MovieDbContext(options))
            {
                MovieRepository movieRepository = new MovieRepository(context);
                List movies == movieRepository.GetAll()
    
                Assert.Equal(3, movies.Count);
            }
    }
    

    Note: Don't forget to install Microsoft.EntityFrameworkCore.InMemory nuget package as follows:

    Install-Package Microsoft.EntityFrameworkCore.InMemory

    For more details: Testing with InMemory

提交回复
热议问题