Mocking IObjectSet <T> with Rhino Mocks

Is there a way to use Rhino Mocks to create a Stub for 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 static helper method, GenerateFakeProjectListI simply create objects of the specified type and add them to the stub using the method AddObjecton IObjectSet:

public static IObjectSet<Project> GenerateFakeProjectList(IObjectSet<Project> projectsObjectSet)
{     
   projectsObjectSet.AddObject(new Project()
   {
     Categories = null,
     DateCreated = DateTime.Now.AddDays(-10),
    .......
+3
source share
3 answers

I would use a specific instance or a simple fake. This interface has a small number of methods, and the implementation looks trivial. The mocking interface just adds unnecessary complexity.

+2
source

, , IObjectSet<T>, . , :

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; }
        }
    }
+6

Since you are mocking the interface, there is no code for everyone. Just set up a stub for your interface, and then close the Projects property to return what you want (I assume that it Projectsis a property, but you did not specify a definition for 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"}
                                                });
+1
source

Source: https://habr.com/ru/post/1796680/


All Articles