Mock DbQuery to use FromSql from unit tests

entity-framework-core unit-testing


I am using EF Core in a projet to get stored procedure calling. In my context i have the following :

public class MyContext : DbContext
    public DbQuery<User> UserQuery { get; set; }

    public MyContext(DbContextOptions<MyContext> options) : base(options) { }

And i call the stored procedure like this :

public virtual async Task<User> GetUserAsync(string name)
    return await MyContext.Query<User>()
        .FromSql($"EXEC [dbo].[GetUser], @Login = {name}")

Code is working fine. I need to test this method in unit tests, i'm using InMemoryDatabase to mock my context MyContext like this :

public async Task GetUserAsync_should_return_first_user_with_login_and_password_if_exists()
    // Arrange
    var users = new List<User>
        new User()
            Login = "",
            Password = "pass1",

    var options = new DbContextOptionsBuilder<MyContext>()
        .UseInMemoryDatabase(databaseName: "BddName")
    var context = new MyContext(options);
    var loginProvider = A.Fake<LoginProvider>(opts => opts.WithArgumentsForConstructor(() => new LoginProvider(context)));

    // Act

    // Assert

And i have no idea how can i set my list into the result of the stored procedure called from DbQuery. I tried to follow this article : but it works for DbSet only and not DbQuery. I need some advices for this case.

Thanks in advance.

7/8/2019 8:44:40 AM

Popular Answer

The link in the OP does apply to the DbQuery type as well, as you're mocking the provider. Both DbSet and DbQuery work in the same way in this regard.

See for a previous answer on the topic.

10/16/2019 12:08:16 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow