如何使moq使用内存数据库而不是真实数据库?

问题描述 投票:0回答:0

我对 NUnit 测试有疑问。我有一个 EF Core 5 项目,我想对其进行最小起订量测试。我听说最小起订量创建了一个内存数据库以不接触真实数据库。无论如何,当我运行测试时,我会在数据库中看到新记录。

    [TestCase]
    public void AddProductInDatabase()
    {
        var data = new List<Vehicle>()
        {
            new Vehicle("testBrand1", "testModel1",1999 ,"Yellow", 1, 1, 123, 1, 124,false)
        }.AsQueryable();

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

        var mockContext = new Mock<TDIcontext>();
        mockContext.Setup(c => c.Vehicles).Returns(mockSet.Object);

        var service = new VehicleBusiness(mockContext.Object);
        data.ToList().ForEach(p => service.AddVehicle(p));

        var vehicle = service.GetVehicle(1);
        Assert.AreEqual(1, vehicle.Id);
    }
entity-framework-core nunit moq
© www.soinside.com 2019 - 2024. All rights reserved.