我做了一个DbContext的模拟,并填充了测试数据。DbSet 是一个受保护的类,因此无法模拟结果,因此我找到了一个扩展方法。
public static class DbSetMocking
{
private static Mock<DbSet<T>> CreateMockSet<T>(IQueryable<T> data)
where T : class
{
var queryableData = data.AsQueryable();
var mockSet = new Mock<DbSet<T>>();
mockSet.As<IQueryable<T>>().Setup(m => m.Provider)
.Returns(queryableData.Provider);
mockSet.As<IQueryable<T>>().Setup(m => m.Expression)
.Returns(queryableData.Expression);
mockSet.As<IQueryable<T>>().Setup(m => m.ElementType)
.Returns(queryableData.ElementType);
mockSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator())
.Returns(queryableData.GetEnumerator());
return mockSet;
}
public static IReturnsResult<TContext> ReturnsDbSet<TEntity, TContext>(this IReturns<TContext, DbSet<TEntity>> setup, TEntity[] entities)
where TEntity : class
where TContext : DbContext
{
var mockSet = CreateMockSet(entities.AsQueryable());
return setup.Returns(mockSet.Object);
}
public static IReturnsResult<TContext> ReturnsDbSet<TEntity, TContext>(this IReturns<TContext, DbSet<TEntity>> setup, IQueryable<TEntity> entities)
where TEntity : class
where TContext : DbContext
{
var mockSet = CreateMockSet(entities);
return setup.Returns(mockSet.Object);
}
public static IReturnsResult<TContext> ReturnsDbSet<TEntity, TContext>(this IReturns<TContext, DbSet<TEntity>> setup, IEnumerable<TEntity> entities)
where TEntity : class
where TContext : DbContext
{
var mockSet = CreateMockSet(entities.AsQueryable());
return setup.Returns(mockSet.Object);
}
}
要创建 DbContext 的模拟,请执行以下操作:
var db = new Mock<DbContext>();
//Populate
this.db.Setup(x => x.MyObjects).ReturnsDbSet(
new List<MyObject>
{
new MyObject{Id=1, Description="Test"},
}
);
其次,我正在尝试扩展模拟以包括 Find(id) 和 FindAsync(id) 方法。这些方法被放置在 DbSetMocking 类中。查找方法工作正常:
mockSet.Setup(m => m.Find(It.IsAny<object[]>()))
.Returns<object[]>(id => StaticMethodtoFindStuff<T>(queryableData, id));
但是,我无法让 FindAsync 方法工作。这是我到目前为止尝试过的:
mockSet.Setup(m => m.FindAsync(It.IsAny<object[]>()))
.Returns(Task.FromResult(StaticMethodtoFindStuff<T>(queryableData, 1)));
这个有效,但是我无法访问函数设置的参数。尝试了这个,编译工作正常,但在执行时失败,出现错误 msg:
类型为"System.Object[]"的对象不能转换为类型"System.Threading.Tasks.Task'1[System.Object[]]"。
mockSet.Setup(m => m.FindAsync(It.IsAny<object[]>()))
.Returns<Task<object[]>>(d =>
{
return Task.FromResult(StaticMethodtoFindStuff<T>(queryableData, d));
});
有人知道如何实现此功能吗?
通了。原来我在那里缺少一个"异步"关键字。代码是:
mockSet.Setup(m => m.FindAsync(It.IsAny<object[]>()))
.Returns<object[]>(async (d) =>
{
return await Task.FromResult(StaticMethodtoFindStuff<T>(queryableData, d));
});
尝试更改此行:
mockSet.Setup(m => m.FindAsync(It.IsAny<object[]>()))
.Returns<Task<object[]>>(d =>
{
return Task.FromResult(StaticMethodtoFindStuff<T>(queryableData, d));
});
自:
mockSet.Setup(m => m.FindAsync(It.IsAny<object[]>()))
.Returns<object[]>(d =>
{
return Task.FromResult(StaticMethodtoFindStuff<T>(queryableData, d));
});
这里的问题是,.Returns<T>
的通用参数T
不是结果的类型,而是第一个参数的类型,在.Setup
方法的函数内部传递 - 对于你的 it's object[]。
查看最小起订量源代码以获取更多信息:
https://github.com/moq/moq4/blob/b2cf2d303ea6644fda2eaf10bad43c88c05b395f/Source/Language/IReturns.Generated.cs
以下是来源的引述,请查看 T1 和 T2 参数注释:
/// <summary>
/// Specifies a function that will calculate the value to return from the method,
/// retrieving the arguments for the invocation.
/// </summary>
/// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam>
/// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam>
/// <param name="valueFunction">The function that will calculate the return value.</param>
/// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return>
/// <example>
/// <para>
/// The return value is calculated from the value of the actual method invocation arguments.
/// Notice how the arguments are retrieved by simply declaring them as part of the lambda
/// expression:
/// </para>
/// <code>
/// mock.Setup(x => x.Execute(
/// It.IsAny<int>(),
/// It.IsAny<int>()))
/// .Returns((int arg1, int arg2) => arg1 + arg2); //I fixed that line, it's different in the documentation and is incorrect
/// </code>
/// </example>
IReturnsResult<TMock> Returns<T1, T2>(Func<T1, T2, TResult> valueFunction);
您还可以看到,它使用可变数量的泛型参数定义了 Return 的多个重载,因此您可以模拟最多包含 16 个参数的方法。