Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

c# - 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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...