public void TestFindById()
        {
            Mock <IUnitOfWork>         uowMock  = new Mock <IUnitOfWork>();
            Mock <IRepository <Post> > repoMock = new Mock <IRepository <Post> >();

            var posts = Enumerable.Range(0, 5).Select(x => new Post()
            {
                Id  = x,
                Url = string.Format("www.someurl{0}", x)
            }).ToList();

            for (int i = 0; i < posts.Count; i++)
            {
                posts[i].PostComments.Add(new PostComment()
                {
                    Comment = string.Format("some test comment {0}", i)
                });
            }

            repoMock.Setup(moq => moq.Get(It.IsInRange(0, 5, Range.Inclusive)))
            .Returns((int id) => posts.SingleOrDefault(x => x.Id == id));


            SomeService service       = new SomeService(uowMock.Object, repoMock.Object);
            var         retrievedPost = service.FindById(2);


            Assert.AreEqual(2, retrievedPost.Id);
        }
Пример #2
0
        public void TestFindById()
        {
            var posts = Enumerable.Range(0, 5).Select(x => new Post()
            {
                Id  = x,
                Url = string.Format("www.someurl{0}", x)
            }).ToList();

            for (int i = 0; i < posts.Count; i++)
            {
                posts[i].PostComments.Add(new PostComment()
                {
                    Comment = string.Format("some test comment {0}", i)
                });
            }

            var queryablePosts = posts.AsQueryable();

            var dbsetMock = CreateMockSet(queryablePosts);

            //NOTE : we need to use the string version of Include as the other one that accepts
            //       an Expression tree is an extension method in System.Data.Entity.QueryableExtensions
            //       which Moq doesn't like
            //
            // So the following will not work, as will result in this sort of Exception from Moq
            //
            //       Expression references a method that does not belong to
            //       the mocked object: m => m.Include<Post,IEnumerable`1>(It.IsAny<Expression`1>())
            //
            // dbsetMock.Setup(m => m.Include(It.IsAny<Expression<Func<Post,IEnumerable<PostComment>>>>()))
            //       .Returns(dbsetMock.Object);
            dbsetMock.Setup(m => m.Include("PostComments")).Returns(dbsetMock.Object);



            var mockContext = new Mock <SachaContextTestDouble>();

            mockContext.Setup(c => c.Posts).Returns(dbsetMock.Object);

            var service       = new SomeService(mockContext.Object);
            var retrievedPost = service.FindById(1);

            Assert.AreEqual(retrievedPost.Id, 1);
            Assert.IsNotNull(retrievedPost.PostComments);
            Assert.AreEqual(retrievedPost.PostComments.Count, 1);
        }