编程语言
首页 > 编程语言> > c# – 阻止孩子们在Moq / AutoFixture中嘲笑

c# – 阻止孩子们在Moq / AutoFixture中嘲笑

作者:互联网

我有一个问题,其中moq或Ploeh.AutoFixture.AutoMoq正在模拟所有子接口,在一种情况下我希望其中一个为null.

我使用的是Npoc,它有一个名为IDatabase的接口

 public interface IDatabase : IDatabaseQuery
    {
        IDbConnection Connection { get; }
        IDbTransaction Transaction { get; }

        void AbortTransaction();
        void BeginTransaction();
        void BeginTransaction(IsolationLevel? isolationLevel);
        void CompleteTransaction();
        IDataParameter CreateParameter();
        int Delete(object poco);
        int Delete<T>(object pocoOrPrimaryKey);
        int Delete<T>(Sql sql);
        int Delete<T>(string sql, params object[] args);
        int Delete(string tableName, string primaryKeyName, object poco);
        int Delete(string tableName, string primaryKeyName, object poco, object primaryKeyValue);
        void Dispose();
        Transaction GetTransaction();
        Transaction GetTransaction(IsolationLevel? isolationLevel);
        object Insert(object poco);
        object Insert(string tableName, string primaryKeyName, object poco);
        object Insert(string tableName, string primaryKeyName, bool autoIncrement, object poco);
        void Save(object poco);
        void Save(string tableName, string primaryKeyName, object poco);
        IDatabase SetTransaction(IDbTransaction tran);
        int Update(object poco);
        int Update<T>(Sql sql);
        int Update(object poco, IEnumerable<string> columns);
        int Update(object poco, object primaryKeyValue);
        int Update<T>(string sql, params object[] args);
        int Update(object poco, object primaryKeyValue, IEnumerable<string> columns);
        int Update(string tableName, string primaryKeyName, object poco);
        int Update(string tableName, string primaryKeyName, object poco, IEnumerable<string> columns);
        int Update(string tableName, string primaryKeyName, object poco, object primaryKeyValue);
        int Update(string tableName, string primaryKeyName, object poco, object primaryKeyValue, IEnumerable<string> columns);
    }

我不想要IDbTransaction Transaction {get;被嘲笑,因为我希望它是null但是它被嘲笑了.

然后我还有一个具有IDatabase接口的IUnitOfWork.

  public interface IUnitOfWork : IDisposable 
    {
        void Commit();
        IDatabase Db { get; }
        void SetOneTimeCommandTimeout(int timeout);
        void SetGlobalCommandTimeout(int timeout);
        void BeginTransaction();

    }

//代码

 fixture = new Fixture().Customize(new AutoMoqCustomization());
 fixture.Freeze<Mock<IDatabase>>();
 var test = fixture.CreateAnonymous<MyService>();

由于Transaction是一个只读属性,我不知道如何将其设置为null.

解决方法:

尝试

  fixture = new Fixture().Customize(new AutoMoqCustomization());
  var mock = fixture.Freeze<Mock<IDatabase>>();
  mock.SetupGet(o => o.Transaction).Returns((IDbTransaction)null);
  var test = fixture.CreateAnonymous<MyService>();

标签:c,mocking,moq,autofixture
来源: https://codeday.me/bug/20190625/1285692.html