为 EF 数据库上下文设置模拟对象以测试存储库方法



我有实体框架存储库,它从sqldb获取行程信息。我已经创建了存储库,并在构造函数上注入了 dbContext 并使用该上下文执行数据库操作。

 public class WorldRepository : IWorldRepository
    {
        private WorldContext _context;
        public WorldRepository(WorldContext context)
        {
            _context = context;
        }
        public void AddSop(string tripName, Stop newStop)
        {
            var trip = GetTipByName(tripName);
            if (trip != null)
            {
                trip.Stops.Add(newStop);
                _context.Stops.Add(newStop);
            }
        }
        public void AddTrip(Trip trip)
        {
            _context.Add(trip);
        }
        public IEnumerable<Trip> GetAllTrips()
        {
            return _context.Trips.ToList();
        }
}

现在我正在尝试使用最小起订量进行测试,但这无济于事.我无法测试在我的方法上编写的任何逻辑,因为它查询的是模拟对象而不是我的实现。

  // private Mock<IWorldRepository> _mockWorld;
        [TestMethod]
        public void Test_AddTrips()
        {
            //Arrange
            // WorldRepository repo = new WorldRepository(null);
            Mock<IWorldRepository> _mockWorld = new Mock<IWorldRepository>();
            var repo = _mockWorld.Object;
            //Act
            repo.AddSop("Sydney", new Stop
            {
                Arrival = DateTime.Now,
                Id = 2,
                Latittude = 0.01,
                Longitude = 0.005,
                Name = "Test Trip",
                Order = 5
            });
            repo.SaveChangesAsync();
            var count = repo.GetAllTrips().Count();
            //Assert
            Assert.AreEqual(1, count);

        }

这是WorldContext的代码。

public class WorldContext:DbContext
    {
        private IConfigurationRoot _config;
        public WorldContext(IConfigurationRoot config,DbContextOptions options)
            :base(options)
        {
            _config = config;
        }
        public DbSet<Trip> Trips { get; set; }
        public DbSet<Stop> Stops{ get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer(_config["ConnectionStrings:WorldCotextConnection"]);
        }
    }

我假设您正在尝试模拟WorldContextand以将其与您的存储库实例一起使用,因此我们需要先模拟它。为此,请创建一个接口 worlddbcontext .

public interface IWorldContext
    {
        DbSet<Stop> Stops { get; set; }
        DbSet<Trip> Trips { get; set; }
    }

现在你想要的是模拟依赖关系和测试主题。

在这种情况下,您要模拟WorldDbContext,模拟DbSet<Stop>并测试AddSop方法。

为了创建一个模拟的DbSet,我指的是MSDN,EF测试与模拟框架,正如Jasen在评论中提到的。

 private Mock<IWorldContext> _context;
 private WorldRepository _repo;
        [TestMethod]
        public void Test_AddTrips()
        {
            ////Arrange          
            var data = new List<Stop> {
                 new Stop
                {
                    Arrival = DateTime.Now.AddDays(-15),
                    Id = 1,
                    Latittude = 0.05,
                    Longitude = 0.004,
                    Name = "Test Trip01",
                    Order = 1
                },
                   new Stop
                {
                    Arrival = DateTime.Now.AddDays(-20),
                    Id = 2,
                    Latittude = 0.07,
                    Longitude = 0.015,
                    Name = "Test Trip02",
                    Order = 2
                }
            }.AsQueryable();
            var mockSet = new Mock<DbSet<Stop>>();
            mockSet.As<IQueryable<Stop>>().Setup(m => m.Provider).Returns(data.Provider);
            mockSet.As<IQueryable<Stop>>().Setup(m => m.Expression).Returns(data.Expression);
            mockSet.As<IQueryable<Stop>>().Setup(m => m.ElementType).Returns(data.ElementType);
            mockSet.As<IQueryable<Stop>>().Setup(m => m.GetEnumerator()).Returns( data.GetEnumerator());

            _context = new Mock<IWorldContext>();
           //Set the context of mock object to  the data we created.
            _context.Setup(c => c.Stops).Returns(mockSet.Object);
           //Create instance of WorldRepository by injecting mock DbContext we created
            _repo = new WorldRepository(_context.Object);    

            //Act
            _repo.AddSop("Sydney",
                new Stop
                {
                    Arrival = DateTime.Now,
                    Id = 2,
                    Latittude = 0.01,
                    Longitude = 0.005,
                    Name = "Test Trip",
                    Order = 5
                });
            _repo.SaveChangesAsync();
            var count = _repo.GetAllTrips().Count();
            //Assert
            Assert.AreEqual(3, count);

        }

此外,有一个精彩的模块(只是一个参考,没有认可或其他任何东西)由Mosh在Testing Repository模块上复数视线,他已经非常详细地解释了这一点。

如果你想

测试WorldRepository,你需要创建这种类型的真实对象并模拟它的所有外部依赖关系 - 在你的例子中是WorldContext。

因此,测试的正确设置应该是这样的:

var contextMock = new Mock<WorldContext>();
contextMock.Setup(...); //setup desired behaviour
var repo = new WorldRepository(contextMock.Object);

最新更新