Mock DbQuery to use FromSql from unit tests

entity-framework-core unit-testing

Question

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}")
        .FirstOrDefaultAsync();
}

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

[Fact]
public async Task GetUserAsync_should_return_first_user_with_login_and_password_if_exists()
{
    // Arrange
    var users = new List<User>
    {
        new User()
        {
            Login = "test@outlook.fr",
            Password = "pass1",
        },
    };

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


    // Act

    // Assert
    context.Dispose();
}

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 : https://nodogmablog.bryanhogan.net/2017/11/unit-testing-entity-framework-core-stored-procedures/ but it works for DbSet only and not DbQuery. I need some advices for this case.

Thanks in advance.

1
1
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 https://stackoverflow.com/a/56940311/2975810 for a previous answer on the topic.

0
10/16/2019 12:08:16 AM


Related Questions





Related

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