简体   繁体   English

C#如何Moq实体框架DbSet添加方法

[英]C# How to Moq entityframework DbSet Add method

I am trying to create a test to test entity framework Add method. 我正在尝试创建一个测试以测试实体框架的Add方法。 Can anyone help how to mock the DbSet.Add method. 任何人都可以帮助模拟DbSet.Add方法。 I have tried as below but not working. 我已经尝试了如下但不能正常工作。 What am I doing wrong? 我究竟做错了什么?

The result I am getting is null after repository.Insert ... 我得到的结果是repository.Insert后为null

Test.cs: Test.cs:

var productToCreate = new Product { Name = "Added", Description = "Added" };        

var result = repository.InsertAsync(objToCreate, userContext).Result;
Assert.AreEqual(result.Name, "Added");  

Mock.cs Mock.cs

internal static DbSet<T> GetMockedDataSet<T>(IEnumerable<T> data) where T : class
{
    // Create a mocked data set that contains the data
    var set = new Mock<DbSet<T>>();
    set.As<IDbAsyncEnumerable<T>>()
        .Setup(m => m.GetAsyncEnumerator())
        .Returns(new TestDbAsyncEnumerator<T>(data.GetEnumerator()));
    set.As<IQueryable<T>>()
        .Setup(m => m.Provider)
        .Returns(new TestDbAsyncQueryProvider<T>(data.AsQueryable().Provider));
    set.As<IQueryable<T>>().Setup(m => m.Expression).Returns(data.AsQueryable().Expression);
    set.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(data.AsQueryable().ElementType);
    set.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

    set.Setup(x => x.AsNoTracking()).Returns(set.Object);
    set.Setup(x => x.Add(It.IsAny<T>())).Callback<T>((s) => data.Concat(new[] { s }));

    // Return the mock
    return set.Object;
}

Repository: 仓库:

public async Task<Product> InsertAsync(Product input)
{
    using (var ctx = .....))
    {
        var added = ctx.Set<Product>().Add(input);

        await ctx.ValidateAndSaveAsync();

        return added;
    }
}

According to how the Add method is being used in the method under test... 根据被测方法中Add方法的使用方式...

var added = ctx.Set<Product>().Add(input);

...there should also be a Returns in the setup that returns the argument that was entered, if that is the desired functionality. ...如果设置是期望的功能,则在安装程序中还应该有一个Returns返回所输入的参数。

set.Setup(x => x.Add(It.IsAny<T>()))
   .Returns<T>(arg => arg)
   .Callback<T>((s) => data.Concat(new[] { s }));

But given that the information about context dependency is unknown... 但是鉴于有关上下文依赖的信息是未知的...

using (var ctx = .....))

It is uncertain if the provided solution will have the desired effect. 不确定所提供的解决方案是否会达到预期的效果。

Additionally if testing an async method, don't mix async and sync calls. 另外,如果测试异步方法,请不要混合使用异步和同步调用。 The following line... 下一行...

var result = repository.InsertAsync(objToCreate, userContext).Result;

...can cause deadlocks. ...可能会导致死锁。

Make the test method async all the way. 使测试方法一直保持异步。

[TestMethod]
public async Task InsertAsync_Should_Return_Product() {
    //...other code

    var expected = new Product { Name = "Added", Description = "Added" };        

    var actual = await repository.InsertAsync(expected, userContext);

    Assert.AreEqual(expected.Name, actual.Name);  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM