D
D
Dmitry2016-09-03 21:46:31
ASP.NET
Dmitry, 2016-09-03 21:46:31

How to do unit tests with Moq?

Hello! The question is, for example, there is a repository

public class UserRepository
    {
        private EFDbContext _context;

        public UserRepository(EFDbContext context)
        {
            _context = context;
        }

        public IReadOnlyCollection<User> GetAll()
        {
            return _context.User.ToList();
        }
    }

and there is a service
public class UserSvc
{

private readonly IUserRepository userRepo;
 public UserSvc(IUserRepository userRepo)
{
this.userRepo = userRepo
}

public IReadOnlyCollection<User> GetAll()
{
return  userRepo.GetAll();
}
}

and here is the question, in order to test the GetAll method in UserSvc, I have to lock IUserRepository in order to test a pure service. But I still want to test the repository, in this case I need to refactor the repository so that I can mock EFDbContext, but is it possible to do without refactoring and without mocking EFDbContext, but just create a new repository instance, because this particular implementation of the repository uses EF, then you can do not bother with the EFDbContext mocan, do I understand correctly, or did I make a mistake somewhere? I am just starting to understand this topic.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Kovalsky, 2016-09-04
@dmitryKovalskiy

Depends on what you want to test. In this case, it is quite possible that you should already write integration tests, and not unit. Then you don't need to wet.

D
Daniil Danilov, 2016-09-05
@kempendyi

The question is not entirely clear, if you want to test the UserRepository, hide the context behind the interface and write a mock.
Then you can emulate the "bad" behavior of the object (context), and based on this, expand the logic of the repository. The situation is similar to the UserSvc that you actually described (I have to lock IUserRepository to test a pure service. ).
At the initial stage, I would recommend that you write mocks yourself, then use various frameworks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question