This is because you rely on an implementation detail (the fact that your IMyDbContext also implements IObjectContextAdapter ), which you should not be aware of. In unit test, an instance of IMyDbContext is actually a proxy server generated by a fake framework, and does not implement IObjectContextAdapter .
Since CommandTimeout does not make sense for this fake DbContext , I suggest you try to make and install CommandTimeout only if the pursuit is CommandTimeout :
var objectContextAdapter = usingDb as IObjectContextAdapter; if (objectContextAdapter != null) objectContextAdapter.ObjectContext.CommandTimeout = 120;
Thus, the CommandTimeout will be installed in the real runtime, but not in the unit test (which does not matter, since the layout does not actually query the database)
EDIT: in fact, the best and cleanest option would be to modify IMyDbContext to show a way to set CommandTimeout :
interface IMyDbContext { ... int CommandTimeout { get; set; } } class MyDbContext : IMyDbContext { ... public int CommandTimeout { get { return ((IObjectContextAdapter)this).ObjectContext.CommandTimeout; } set { ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = value; } } }
And now you can just do:
usingDb.CommandTimeout = 120;
without worrying about the real type of context. The mocking structure will simply create a dummy implementation for this property.
Thomas levesque
source share