Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq Entity Frameworks ExecuteSQLCommand

I've read that when using moq you cannot mock a non-virtual function. I've also read that this should be possible now.. Is that true? If so, then I'd like to mock the following query:

DatabaseContext.Database.ExecuteSqlCommand(updateQuery, newValue);

I'm overriding the Context in my test as so

DAL.Context.DatabaseContext = mockContext.Object;

I've tried this setup, but it seems the query stills goes agains my regular db

mockContext.Setup(c => c.Set<AppSalesAndResult>()).Returns(mockBudgetData.Object);

Any ideas, could perhaps the executesqlcommand be replaced with something else so that the row above would catch any udpates to the set? I use executesqlcommand due to performance reasons when updating multiple rows at once. Regular EF is too slow

UPDATE:

Reading the following post, How to Moq Entity Framework SqlQuery calls I wonder if a similar implementation would work for ExecuteSQLCommand...

like image 469
JohanLarsson Avatar asked Oct 30 '14 22:10

JohanLarsson


1 Answers

What I have done to being able to Mock ExecuteSqlCommand, which is not possible to do in DataBase class, was to create the same method in my DbContext inheritance but this time virtual, and call the Database.ExecuteSqlCommand

public class MyDbContext : DbContext
{
    public virtual int ExecuteSqlCommand(string sql, params object[] parameters)
    {
        return Database.ExecuteSqlCommand(sql, parameters);
    }
    public virtual int ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, string sql, params object[] parameters)
    {
        return Database.ExecuteSqlCommand(transactionalBehavior, sql, parameters);
    }

Then I changed my business code to call this created method (Not Database method):

DatabaseContext.ExecuteSqlCommand(updateQuery, newValue);

Then, it works

like image 122
mqueirozcorreia Avatar answered Sep 20 '22 14:09

mqueirozcorreia