C#C
C#13mo ago
Pieter

Mock UserManager in unit tests (Student)

How should I mock the UserManager class when I want to make tests for a service which has the UserManager as a dependancy?

In my test i need to create an instance of TripsService:
c#
public class TripService
{
    private readonly ITripRepository _tripRepository;
    private readonly UserManager<User> _userManager;
    private readonly IUnitOfWork _unitOfWork;
    private readonly HttpClient _httpClient;
    private readonly IConfiguration _config;

    public TripService(ITripRepository tripRepository, UserManager<User> userManager, IUnitOfWork unitOfWork, HttpClient httpClient, IConfiguration config)
    {
        _unitOfWork = unitOfWork;
        _tripRepository = tripRepository;
        _userManager = userManager;
        _httpClient = httpClient;
        _config = config;
    }


Now I need to an instance of TripsService but I can't because I need to somehow mock the UserManager. I can't seem to find a way to.

c#
    public class TripServiceTests
    {
        private readonly Mock<ITripRepository> _mockTripRepository;
        private readonly Mock<IUnitOfWork> _mockUnitOfWork;
        private readonly Mock<UserManager<User>> _mockUserManager;
        private readonly Mock<HttpClient> _mockHttpClient;
        private readonly Mock<IConfiguration> _mockConfig;

        private readonly TripService _tripService;

        public TripServiceTests()
        {
            _mockTripRepository = new Mock<ITripRepository>();
            _mockUnitOfWork = new Mock<IUnitOfWork>();
            _mockUserManager = new Mock<UserManager<User>>(Mock.Of<IUserStore<User>>());
            _mockHttpClient = new Mock<HttpClient>();
            _mockConfig = new Mock<IConfiguration>();

            _tripService = new TripService(
                _mockTripRepository.Object,
                _mockUserManager.Object,
                _mockUnitOfWork.Object,
                _mockHttpClient.Object,
                _mockConfig.Object
            );
        }


Thank You!
Was this page helpful?