How can I fake ObjectContext?
How can I fake an ObjectContext when unit testing? I have created my generic repository that excepts an ObjectContext, faked the ObjectSets, but I can't figure out how to create and pass a fake ObjectContext containing the fake ObjectSets into my repository. My repository accepts a class of type ObjectContext.
Any ideas?
public class FakeObjectSet<T> : IObjectSet<T> where T : class {
HashSet<T> _data;
IQueryable _query;
public FakeObjectSet(){
this._data = new HashSet<T>();
this._query = this._data.AsQueryable();
}
public void AddObject(T Item) {
this._data.Add(Item);
}
public void Attach(T Item) {
this._data.Add(Item);
}
public void DeleteObject(T Item) {
this._data.R开发者_运维问答emove(Item);
}
public void Detach(T Item) {
this._data.Remove(Item);
}
public IEnumerator<T> GetEnumerator() {
return this._data.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return _data.GetEnumerator();
}
public Type ElementType {
get { return _data.AsQueryable().ElementType; }
}
public Expression Expression {
get { return _data.AsQueryable().Expression; }
}
public IQueryProvider Provider {
get { return _query.Provider; }
}
}
My fake objectset implementation
public class FakeJobSet : FakeObjectSet<Job>{
}
and my fake context class:
public class FakeCentralRepositoryContext{
public FakeCentralRepositoryContext(){
this.Jobs = new FakeJobSet();
}
public IObjectSet<Job> Jobs
{
get; private set;
}
}
Your repository cannot accept instance of ObjectContext
- you must define your custom interface implemented by both you real derived context and fake context. Your repository must accept that interface. Anyway faking contexts is waste of time and completely bad approach to testing code using EF.
Modify your repository to take IObjectSet rather than ObjectSet then you can pass your fake context into the repository the same way you pass in the real implementation. Alternatively, use a IOC to inject the context.
I would avoid faking/mocking ObjectContext as this object presents complex inner workings, and to do so, defeats the purpose of relying on Entity Framework for taking care of the data layer abstraction.
Check out the post at How to mock ObjectContext or ObjectQuery in Entity Framework? for a better approach to do unit tests with EF.
Hope this helps!
精彩评论