为EF dbcontext设置模拟对象以测试存储库方法

时间:2017-10-19 22:55:05

标签: c# entity-framework unit-testing moq

我有entityframework repo,它从sqldb获取行程信息。我已经创建了repo,并在构造函数上注入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();
        }
}

现在我正在尝试使用MOQ进行测试,但这没有用。我无法测试我的方法上写的任何逻辑,因为它正在查询模拟对象而不是我的实现。

  // 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"]);
        }
    }

2 个答案:

答案 0 :(得分:4)

我假设您正在尝试模拟WorldContextand将其与您的repo实例一起使用,因此我们需要首先模拟它。为此,请为worlddbcontext创建一个界面。

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

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

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

要创建模拟DbSet,我在评论中引用了{em> Jasen 中提到的MSDN, EF Testing with Mocking framework

 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);


        }

此外,module Testing Repository模块上的Mosh复数形式有一个精彩的{{3}}(只是参考,没有认可或其他任何内容),他已详细解释了这一点。< / p>

答案 1 :(得分:1)

如果你想测试WorldRepository,你需要创建这种类型的真实对象并模拟所有它的外部依赖 - 在你的情况下是WorldContext。

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

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