【问题标题】:Mocked DbSet not returning an object模拟 DbSet 不返回对象
【发布时间】:2014-09-22 18:43:44
【问题描述】:

我正在尝试通过使用 Moq 模拟数据来测试更新功能。我正在使用实体框架 6。

我可以打印出DbSet 的计数,这是预期的数量。但是,当它试图选择一个对象时,它会抛出一个异常,NullReferenceException: Object reference not set to an instance of an object.

这是我的测试类,它设置了模拟的 DbSetsDbContext

[TestFixture]
public class ProductControllerTest
{
    private ProductController controller;
    private IProductRepository productRepo;
    private IUnitOfWork unitOfWork;
    private IBrandRepository brandRepo;
    private ICategoryRepository categoryRepo;
    private ISegmentRepository segmentRepo;
    private ITypeRepository typeRepo;
    private IEnumerable<Product> productList;

    [SetUp]
    public void Init()
    {
        IEnumerable<Brand> brandList = new List<Brand>{
            new Brand{
                Id = 1,
                Name = "Unknown"
            },
            new Brand{
                Id = 2,
                Name = "Clorox"
            },
            new Brand{
                Id = 3,
                Name = "Glad"
            }
        };
        var brandData = brandList.AsQueryable();

        productList = new List<Product>{
            new Product{
                Id = "0000000001",
                ParentAsin = "0000000010",
                Title = "Mocked Product #1",
                ReleaseDate = DateTime.Now,
                BrandId = 1,
                CategoryId = 1,
                SegmentId = 1,
                TypeId = 1,
                Brand = brandList.ElementAt(0)
            }, 
            new Product{
                Id = "0000000002",
                ParentAsin = "0000000010",
                Title = "Mocked Product #2",
                ReleaseDate = DateTime.Now,
                BrandId = 1,
                CategoryId = 1,
                SegmentId = 1,
                TypeId = 1,
                Brand = brandList.ElementAt(0)
            },
            new Product{
                Id = "0000000003",
                ParentAsin = "0000000010",
                Title = "Mocked Product #3",
                ReleaseDate = DateTime.Now,
                BrandId = 2,
                CategoryId = 3,
                SegmentId = 3,
                TypeId = 2,
                Brand = brandList.ElementAt(1)
            }
        };
        var productData = productList.AsQueryable();

        brandList.ElementAt(1).Products.Add(productList.ElementAt<Product>(2));

        var mockProductSet = new Mock<DbSet<Product>>();
        mockProductSet.As<IQueryable<Product>>().Setup(m => m.Provider).Returns(productData.Provider);
        mockProductSet.As<IQueryable<Product>>().Setup(m => m.Expression).Returns(productData.Expression);
        mockProductSet.As<IQueryable<Product>>().Setup(m => m.ElementType).Returns(productData.ElementType);
        mockProductSet.As<IQueryable<Product>>().Setup(m => m.GetEnumerator()).Returns(productData.GetEnumerator());

        var mockBrandSet = new Mock<DbSet<Brand>>();
        mockBrandSet.As<IQueryable<Brand>>().Setup(m => m.Provider).Returns(brandData.Provider);
        mockBrandSet.As<IQueryable<Brand>>().Setup(m => m.Expression).Returns(brandData.Expression);
        mockBrandSet.As<IQueryable<Brand>>().Setup(m => m.ElementType).Returns(brandData.ElementType);
        mockBrandSet.As<IQueryable<Brand>>().Setup(m => m.GetEnumerator()).Returns(brandData.GetEnumerator());

        var mockContext = new Mock<ApplicationDbContext>() { CallBase = true };
        mockContext.Setup(m => m.Set<Product>()).Returns(mockProductSet.Object);
        mockContext.Setup(m => m.Set<Brand>()).Returns(mockBrandSet.Object);

        unitOfWork = new UnitOfWork(mockContext.Object);
        brandRepo = new BrandRepository(mockContext.Object);
        productRepo = new ProductRepository(mockContext.Object);
        controller = new ProductController(productRepo, unitOfWork, brandRepo, categoryRepo, segmentRepo, typeRepo);
    }

    [Test]
    public void TestReturnEditedModel()
    {
        Product product = productList.ElementAt<Product>(1);
        product.BrandId = 3;
        product.CategoryId = 2;
        product.SegmentId = 2;
        product.TypeId = 3;

        controller.Edit(product, "Return value");

        Product result = productRepo.Get(product.Id);
        Assert.AreEqual(product.Id, result.Id);
        Assert.AreEqual(3, result.BrandId);
        Assert.AreEqual(2, result.CategoryId);
        Assert.AreEqual(2, result.SegmentId);
        Assert.AreEqual(3, result.TypeId);
    }
}

我只提供了失败的测试。

这里是被调用的控制器函数

[HttpPost]
public ActionResult Edit([Bind(Include = "Id,Title,ParentAsin,ReleaseDate,BrandId,CategoryId,SegmentId,TypeId")]Product model, string returnAction)
{
    if(!ModelState.IsValid)
    {
        Dictionary<string, int> selectedIds = new Dictionary<string, int>();
        selectedIds.Add("BrandId", model.BrandId);
        selectedIds.Add("CategoryId", model.CategoryId);
        selectedIds.Add("SegmentId", model.SegmentId);
        selectedIds.Add("TypeId", model.TypeId);
        PopulateAllDropDownLists(selectedIds);
        return View(model);
    }

    model.Brand = _brandRepo.Get(model.BrandId);
    model.Category = _categoryRepo.Get(model.CategoryId);
    model.Segment = _segmentRepo.Get(model.SegmentId);
    model.Type = _typeRepo.Get(model.TypeId);
    _repository.Update(model);
    _unitOfWork.SaveChanges();
    return RedirectToAction(returnAction);
}

_brandRepoIBrandRepository 类型,在所有实现和继承之后,函数Get() 位于通用存储库类中。

这里是被调用的 Get 函数。

public virtual TEntity Get(TId id)
{
    return this.DbSet.Single(x => (object)x.Id == (object)id);
}

返回行是引发错误的原因。

由于这是一个测试并且我在模拟数据,我知道传入的 Id 是正确的。它以int 开头,BrandId 也是int,但要使其通用,属性类型为TId 是接口TEntity 的通用类型,所有模型都实现。

这里是 TEntity

public interface IEntity<TId>
{
    /// <summary>
    /// Gets or sets the unique identifier.
    /// </summary>
    /// <value>The unique identifier.</value>
    TId Id { get; set; }
}

我不确定这是模拟问题还是使用泛型类型的问题。有人可以帮忙吗?

【问题讨论】:

  • 你能用更小的单元测试重现这个吗?您的示例中有很多内容。
  • @RyanGates 我从测试设置的代码中取出,我仍然能够重新创建错误。当我查询模拟的DbSet&lt;Brand&gt; 时必须这样做

标签: c# .net entity-framework generics moq


【解决方案1】:

这看起来太复杂了;您可以只使用通用方法为任何 DbSet 创建模拟...

public static class DbSetMock
{
    public static Mock<DbSet<T>> CreateFrom<T>(List<T> list) where T : class
    {
        var internalQueryable = list.AsQueryable();
        var mock = new Mock<DbSet<T>>();
        mock.As<IQueryable<T>>().Setup(x => x.Provider).Returns(internalQueryable.Provider);
        mock.As<IQueryable<T>>().Setup(x => x.Expression).Returns(internalQueryable.Expression);
        mock.As<IQueryable<T>>().Setup(x => x.ElementType).Returns(internalQueryable.ElementType);
        mock.As<IQueryable<T>>().Setup(x => x.GetEnumerator()).Returns(()=> internalQueryable.GetEnumerator());
        mock.As<IDbSet<T>>().Setup(x => x.Add(It.IsAny<T>())).Callback<T>(element => list.Add(element));
        mock.As<IDbSet<T>>().Setup(x => x.Remove(It.IsAny<T>())).Callback<T>(element => list.Remove(element));
        return mock;
    }
}

然后你可以像这样使用它:

 var mockBrandSet = DbSetMock.CreateFrom(brandList);

由于列表中的数据和 DbSet 相同,您可以检查列表以断言您的操作。

【讨论】:

  • 对于 EFCore,不要忘记删除 .As>(),因为没有这样的接口,并且 .As>() 会失败。添加和删​​除的设置将按预期工作。
  • 对于 EFCore,从上下文派生新的 TestDatabaseContext 并将其设置为内存数据库可能更简单。 public TestDatabaseContext(DbContextOptions options) : base(options) { } public static DbContextOptions GetDBOptions() { return new DbContextOptionsBuilder() .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) 。 EnableSensitiveDataLogging() .Options; }
  • 正如一些人在类似帖子中指出的那样,设置 InMemoryDb 会将一个依赖项替换为另一个依赖项,使其更像是一种集成测试。
  • 这当然是真的。但最终,您想要编写涵盖您的业务逻辑的测试,并且您想要一个令人难以置信的快速且易于使用的设置。因此,在这一点上,我会推荐 InMemory 方法而不是 DbSetMock,因为它速度相似,并且没有 .Include .ThenInclude 等扩展方法问题。
【解决方案2】:

如果您在任何时候尝试通过它们的属性而不是通过Set&lt;&gt; 访问 DbSet,如果它们没有设置会导致该问题。尽管调用基础在原始示例中是正确的,但 DbContext 会在内部尝试发现 DbSets 并初始化它们,这在模拟 DbContext 时会失败。这是他们必须在模拟中设置以覆盖默认行为的内容。

var mockContext = new Mock<ApplicationDbContext>();
mockContext.Setup(m => m.Set<Product>()).Returns(mockProductSet.Object);
mockContext.Setup(m => m.Set<Brand>()).Returns(mockBrandSet.Object);
mockContext.Setup(m => m.Products).Returns(mockProductSet.Object);
mockContext.Setup(m => m.Brands).Returns(mockBrandSet.Object);

另外在设置GetEnumerator()时,使用函数允许多次调用

例如

mockProductSet.As<IQueryable<Product>>()
    .Setup(m => m.GetEnumerator())
    .Returns(() => productData.GetEnumerator());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多