【问题标题】:Setting up mock objects for EF dbcontext to test repository methods为 EF dbcontext 设置模拟对象以测试存储库方法
【发布时间】:2017-10-19 22:55:04
【问题描述】:

我有从 sqldb 获取行程信息的 entityframework 存储库。我已经创建了 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"]);
        }
    }

【问题讨论】:

  • 你需要使用 WorldRepository 类和模拟 dbcontext 。你能发布 WorldContext 的代码吗?
  • 您可能应该在模拟 WorldContext,并将其传递给 WorldRepository。
  • 微软提供了一个异步模拟的实现。 msdn.microsoft.com/en-us/library/dn314429(v=vs.113).aspx

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


【解决方案1】:

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

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

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

在这种情况下,您要模拟 WorldDbContext ,模拟 DbSet&lt;Stop&gt; 并测试 AddSop 方法。

为了创建一个模拟 DbSet,我指的是 MSDN, EF Testing with Mocking framework,正如 Jasen 在 cmets 中提到的那样。

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


        }

另外,MoshTesting Repository 模块上的复数视图上有一个出色的module(只是一个参考,没有背书或其他任何东西),他已经非常详细地解释了这一点。

【讨论】:

    【解决方案2】:

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

    所以正确的测试设置应该是这样的:

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

    【讨论】:

      猜你喜欢
      • 2012-02-23
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 2015-01-23
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多