Reputation: 61
I have made a Mock of DbContext and populated with test data. DbSet is a protected class so the result cannot be mocked, so I found an extension method.
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);
}
}
To create a Mock of DbContext:
var db = new Mock<DbContext>();
//Populate
this.db.Setup(x => x.MyObjects).ReturnsDbSet(
new List<MyObject>
{
new MyObject{Id=1, Description="Test"},
}
);
Second, I am trying to extend the Mocks to include Find(id) and FindAsync(id) methods. Theese methods are being place in the DbSetMocking class. Find method works fine:
mockSet.Setup(m => m.Find(It.IsAny<object[]>()))
.Returns<object[]>(id => StaticMethodtoFindStuff<T>(queryableData, id));
However, I cannot get the FindAsync method to work. This is what I have tried so far:
mockSet.Setup(m => m.FindAsync(It.IsAny<object[]>()))
.Returns(Task.FromResult(StaticMethodtoFindStuff<T>(queryableData, 1)));
This one works, but then I dont have access to the parameter set by the function. Tried this one, compiling works fine, but it fails on execution with the error msg:
Object of type 'System.Object[]' cannot be converted to type '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));
});
Anybody have a clue how I can implement this function?
Upvotes: 2
Views: 1899
Reputation: 61
Finally got it figured out. Turned out that I was missing an 'async' keyword there. Code is:
mockSet.Setup(m => m.FindAsync(It.IsAny<object[]>()))
.Returns<object[]>(async (d) =>
{
return await Task.FromResult(StaticMethodtoFindStuff<T>(queryableData, d));
});
Upvotes: 2
Reputation: 2776
Try changing this line:
mockSet.Setup(m => m.FindAsync(It.IsAny<object[]>()))
.Returns<Task<object[]>>(d =>
{
return Task.FromResult(StaticMethodtoFindStuff<T>(queryableData, d));
});
to:
mockSet.Setup(m => m.FindAsync(It.IsAny<object[]>()))
.Returns<object[]>(d =>
{
return Task.FromResult(StaticMethodtoFindStuff<T>(queryableData, d));
});
The thing here is, generic argument T
for .Returns<T>
is not the type of result, but instead, that's the type of first parameter, passed inside function in .Setup
method -- for your it's object[].
Check Moq source code for more info:
Here's a quote from the sources, check T1 and T2 parameter commentaries:
/// <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);
You can also see, that it defines multiple overloads of Returns with variable number of generic parameters, so that you could mock a method with up to 16 parameters.
Upvotes: 1