Is there a way of using Rhino Mocks to generate Stub for an IObjectSet<T>
?
What is am after is something like the following code:
var context = MockRepository.GenerateMock <IContext>();
//generate stub
var mockProjectObjectSet = MockRepository.GenerateStub<IObjectSet<Project>>();
TestObjectSets.GenerateFakeProjectList(mockProjectObjectSet);
context.Expect(p => p.Projects).Return(mockProjectObjectSet);
var projectRepository = new ProjectRepository(context);
In the GenerateFakeProjectList
static helper method, I am simply creating the objects of the type specified and adding them to the stub via the AddObject
method on the IObjectSet
:
public static IObjectSet<Project> GenerateFakeProjectList(IObjectSet<Project> projectsObjectSet)
{
projectsObjectSet.AddObject(new Project()
{
Categories = null,
DateCreated = DateTime.Now.AddDays(-10),
.......
I know I'm late to this party, but here's a simple implementation of IObjectSet<T>
that I've used before. I forget where I got it from:
public class MockObjectSet<T> : IObjectSet<T> where T : class {
readonly List<T> _container = new List<T>();
public void AddObject(T entity) {
_container.Add(entity);
}
public void Attach(T entity) {
_container.Add(entity);
}
public void DeleteObject(T entity) {
_container.Remove(entity);
}
public void Detach(T entity) {
_container.Remove(entity);
}
public IEnumerator<T> GetEnumerator() {
return _container.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return _container.GetEnumerator();
}
public Type ElementType {
get { return typeof(T); }
}
public System.Linq.Expressions.Expression Expression {
get { return _container.AsQueryable<T>().Expression; }
}
public IQueryProvider Provider {
get { return _container.AsQueryable<T>().Provider; }
}
}
I'd use a concrete instance, or a simple fake. That interface has a small number of methods and the implementation appears trivial. Mocking that interface just adds unnecessary complexity.
Since you're mocking an interface, there's no actual code to all. Just set up a stub for your interface and then stub out the Projects property to return what you want (I assume Projects
is a property, but you didn't include a definition of the Project class).
Something like this should work:
var stubSet = MockRepository.GenerateStub<IObjectSet<Project>>();
stubSet.Stub(s => s.Projects).Return(new[]
{
new Project {Categories = null},
new Project {Categories = "abc"}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.