Try
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>();
Question
I am having a problem where either moq or Ploeh.AutoFixture.AutoMoq is mocking all the children interfaces when in one case I want one of them to be null.
I am using Npoc and it has an Interface called 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);
}
I don't want IDbTransaction Transaction { get; }
to be mocked as I want it to be null but it is getting mocked.
I then also have a IUnitOfWork that has the IDatabase interface in it.
public interface IUnitOfWork : IDisposable
{
void Commit();
IDatabase Db { get; }
void SetOneTimeCommandTimeout(int timeout);
void SetGlobalCommandTimeout(int timeout);
void BeginTransaction();
}
// code
fixture = new Fixture().Customize(new AutoMoqCustomization());
fixture.Freeze<Mock<IDatabase>>();
var test = fixture.CreateAnonymous<MyService>();
Since Transaction is a readonly property I don't know how to set it back to null.
Solution
Try
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>();