How to effectively simulate data contexts for unit testing with EF6, MVC, and MOQ

I am trying to add unit testing to a new MVC application and I am following the guide at: http://msdn.microsoft.com/en-us/data/dn314429

The manual describes in detail what I would like to do - testing the results returned to the controller Index () action is sorted correctly, but this example is too far-fetched for my needs. In my case, my ViewModel consists of numerous domain objects, and I find it too tedious to taunt.

The request in my controller action is as follows:

var roles = _db.Roles
            .OrderBy(r => r.Area.Application.Name)
            .ThenBy(r => r.Area.Name)
            .ThenBy(r => r.Name)
            .Select(role =>
                new RoleViewModel
                {
                    RoleName = role.Name,
                    Description = role.Description,
                    ApplicationArea = role.Area.Application.Name + "/" + role.Area.Name,
                    GroupsUsingThisRole = role.RoleGroupMappings
                        .Select(rgm => rgm.Group.Name).ToList()
                }).ToList();

, DBSets. , , , , , , , , .

, ? , , , , , .

+4
2

, . , ? - .

. , , - , . -, :

var roles = roleService
    .GetOrderedRoles()
    .Select(role =>
            new RoleViewModel
            {
                RoleName = role.Name,
                Description = role.Description,
                ApplicationArea = role.Area.Application.Name
                    + "/" + role.Area.Name,
                GroupsUsingThisRole = role.RoleGroupMappings
                    .Select(rgm => rgm.Group.Name).ToList()
            })
    .ToList();

. - ViewModel building. abstract factory pattern:

var roles = roleService
    .GetOrderedRoles()
    .Select(role => roleViewModelFactory.CreateFromRole(role))
    .ToList();

, roleService roleViewModelFactory, . ( ). roleViewModelFactory - .

, - . ? ? , db, . , (mock) db-, , , - .

roleService . :

unit test , EF. LINQ to Objects . , LINQ to LINK (LINQ to Entities) SQL, . (...)

( ), , .

, :

  • , .
  • unit test ,
  • db-
+2

, , . , . - :

public interface IRoleRepository
{
   IQueriable<Role> QueryRoles();
}

mock-:

var roles = new Role[]
{
   new Role
   {
      ...
   },
   ...
};

var mockRepository = new Mock<IRoleRepository>();
mockRepository.Setup(r => r.QueryRoles()).Returns(roles.AsQueryable());
+2

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


All Articles