Moq Entity Frameworks ExecuteSQLCommand

后端 未结 2 866
清酒与你
清酒与你 2021-01-12 04:07

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 f

2条回答
  •  时光取名叫无心
    2021-01-12 04:51

    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

提交回复
热议问题