Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8941071
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T11:12:51+00:00 2026-06-15T11:12:51+00:00

I have a Model : public class Post: { public string Description { get;

  • 0

I have a Model :

public class Post: 
    {
        public string Description { get; set; }
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        public string Name { get; set; }

        public Guid UniqId { get; set; }

        public DateTime CreatedDate { get; set; }

        public byte[] RowVersion { get; set; }

    }

and i have a DataLayer that has EfContext and Iunitofwok pattern

using System.Data.Entity;

    namespace Data
    {
        public interface IUnitOfWork
        {
            IDbSet<TEntity> Set<TEntity>() where TEntity : class;
            int SaveChanges();
        }
    }

using System.Data.Entity;
using DomainModel;





namespace Data
{
    public class EfContext : DbContext, IUnitOfWork
    {
        public DbSet<Post> Post { get; set; }
        public DbSet<Comment> Comments { get; set; }
        public DbSet<Category> Categories { get; set; }
        public EfContext()
            : base("TavanGruop")
        {
        }

        #region IUnitOfWork Members

        public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
        {
            return base.Set<TEntity>();
        }

        #endregion
    }
}

in another project i have repository

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Data;

namespace ServiceLayer.ServiceDbSet
{
    public class ServiceContext<T> : IServiceDbSet<T> where T : class
    {
        private readonly IDbSet<T> _dbSet;

        public  ServiceContext(IUnitOfWork iUnitOfWork)
        {
            _dbSet = iUnitOfWork.Set<T>();
        }

        #region IContext<T> Members

        public bool TryGet(Func<T, bool> predicate, out T entity)
        {
            entity = List(predicate).SingleOrDefault();
            return entity != null;
        }

        public T Get(Func<T, bool> predicate)
        {
            return List(predicate).Single();
        }

        public virtual List<T> List(Func<T, bool> predicate = null)
        {
            IEnumerable<T> result = _dbSet.AsEnumerable();
            if (predicate != null)
                result = result.Where(predicate);
            return result.ToList();
        }

        public T Add(T t)
        {
            _dbSet.Add(t);
            return t;
        }

        public void Delete(Func<T, bool> predicate)
        {
            List(predicate).ToList().ForEach(p => _dbSet.Remove(p));
        }

        public void Delete(T t)
        {
            _dbSet.Remove(t);
        }

        #endregion
    }
}

and service

using Data;
using DomainModel;
using ServiceLayer.ServiceDbSet;

namespace ServiceLayer.EfServices
{
    public class EfPostService : ServiceContext<Post>
    {
        public EfPostService(IUnitOfWork uow)
            : base(uow)
        {
        }
    }
}

and this my services

using Data;
using ServiceLayer.EfServices;

namespace ServiceLayer
{
    public class Services
    {
        private readonly IUnitOfWork _unitOfWork;

        private EfPostService _post;
        private EfCommentService _comment;

        public Services(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public EfPostService Post
        {
            get { return _post ?? new EfPostService(_unitOfWork); }
            set { _post = value; }
        }

        public EfCommentService Comment
        {
            get { return _comment ?? new EfCommentService(_unitOfWork); }
            set { _comment = value; }
        }
    }
}

I use tructuremap for dependency injection

using System;
using System.Web.Mvc;
using System.Web.Routing;
using Data;
using StructureMap;

namespace MVCTemplateProject
{
    public static class StructuremapMvc
    {
        public static void InitStructureMap()
        {
            ObjectFactory.Initialize(x => x.For<IUnitOfWork>().HttpContextScoped().Use(() => new EfContext()));
            ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
        }
    }

    public class StructureMapControllerFactory : DefaultControllerFactory
    {
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            return ObjectFactory.GetInstance(controllerType) as Controller;
        }
    }
}

in base controller i get Iunitofwork

using System.Web.Mvc;
using Data;
using ServiceLayer;

namespace MVCTemplateProject.Controllers
{
    public class BaseController : Controller
    {
        public readonly IUnitOfWork Context;
        public readonly Services DataContext;

        public BaseController(Data.IUnitOfWork context)
        {
            Context = context;
            DataContext = new Services(context);
        }
    }
}

and this my home controller

using System.Web.Mvc;
using Data;
using DomainModel;

namespace MVCTemplateProject.Controllers
{
    public class HomeController : BaseController
    {
        public HomeController(IUnitOfWork context)
            : base(context)
        {
        }

        public ActionResult Index()
        {
            return View(DataContext.Post.List());
        }
    }
}

how can i test index action with moq
i write this test but i get error

public void IndxShouldReturnListOfPage()
{
    var posts = new List<Post>
                    {
                        new Post {Name = "Test"},
                        new Post {Name = "Test"},
                        new Post {Name = "Test"},
                        new Post {Name = "Test"}
                    };
    var efContext = new Mock<EfContext>();
    var mockRepository = new Mock<ServiceLayer.Services>(efContext);
    mockRepository.Setup(x => x.Post.List(It.IsAny<Func<Post, bool>>())).Returns(posts);

    var controller = new HomeController(efContext.Object);

    List<Post> model = controller.DataContext.Post.List();
    var result = controller.Index() as ViewResult;

    Assert.AreEqual(model.Count, 4);
    Assert.AreEqual(string.Empty, result.ViewName);
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T11:12:55+00:00Added an answer on June 15, 2026 at 11:12 am

    i get it and i test the project

     [TestFixture]
        public class PostControllerTest
        {
            #region Setup/Teardown
    
            [SetUp]
            public void Setup()
            {
                UnitOfWork = TestHelper.TestHelper.GetMockUnitOfWork();
                PostDbSet = TestHelper.TestHelper.GetMockPostDbSet();
                Posts = TestHelper.TestHelper.GetFakePosts();
                TagDbSet = TestHelper.TestHelper.GetMockTagDbSet();
                CategoryDbSet = TestHelper.TestHelper.GetMockCategoryDbSet();
    
                PostController = new PostController(UnitOfWork.Object, PostDbSet.Object, CategoryDbSet.Object, TagDbSet.Object);
            }
    
            #endregion
    
            private Mock<IServiceDbSet<Post>> PostDbSet { get; set; }
            private Mock<IServiceDbSet<Tag>> TagDbSet { get; set; }
            private Mock<IServiceDbSet<Category>> CategoryDbSet { get; set; }
            private PostController PostController { get; set; }
            private List<Post> Posts { get; set; }
    
            private Mock<IUnitOfWork> UnitOfWork { get; set; }
    
            [Test]
            public void DetailShouldRedirectToHomePageWhenNotFoundPostOrPostIdIs0()
            {
                PostDbSet.Setup(x => x.Get(It.IsAny<Func<Post, bool>>())).Returns(Posts.Find(post => post.Id == 100));
    
                var redirectToRoutResult =
                    (RedirectToRouteResult) PostController.Details(100);
    
                Assert.AreEqual("Index", redirectToRoutResult.RouteValues["action"]);
                Assert.AreEqual("Home", redirectToRoutResult.RouteValues["Controller"]);
            }
    
            [Test]
            public void DetailShouldShowPostById()
            {
                PostDbSet.Setup(x => x.Get(It.IsAny<Func<Post, bool>>())).Returns(Posts.First());
                var result = PostController.Details(1) as ViewResult;
                var model = result.Model as PostViewModel;
    
                Assert.AreNotEqual(null, model);
                Assert.AreEqual("I Can", model.Title);
                Assert.AreEqual(string.Empty, result.ViewName);
            }
    
            [Test]
            public void ListOfStringTagMustConvertToListOfTagCollection()
            {
                PostViewModel postViewModel = TestHelper.TestHelper.GetFakePostViewModel();
                PostController.Create(postViewModel);
                //Assert.AreEqual(postViewModel.RawTags[0], postViewModel.RawTags.First().Name);
            }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a model public class Foo{ public int Id{get;set;} public string Name {get;
I have the following model: public class Person { public int ID{get;set;} public string
I have a model [Validator(typeof(ContractValidator))] [Route(/contracts, POST)] public class Contract { public int ContractID{get;
I have model public class QuestionViewModel { public string Text { get; set; }
I have the following model: public class Tag { public int Id { get;
I have the following Model: public class DeliveryTracking { public string TrackingRef { get;
I have cratet simple Model public class ModelTest { public string MyValue { get;
I have the following model: public class Contact { public Contact() { Name =
I have a model item public class EntryInputModel { ... [Required(ErrorMessage = Description is
So I have the following model: public class Person { public String FirstName {

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.