How to mock repository in unit test .net core?

ykl
ykl
318 Points
16 Posts

I'm trying to create unit test on service method Service.GetAllUser(). Service method using IUserRepository to fetch users. I'm trying as:

public class Tests
{
    private Mock<IUserRepository> _userRepository;
    private IService _service;

    [SetUp]
    public void Setup()
    {
        _userRepository = new Mock<IUserRepository>();
        _service = new Service(_userRepository.Oject);
    }

    [Test]
    public void ShouldReturnUsers()
    {

        var result = _service.GetAllUser();

        Assert.That(() => result, Is.TypeOf(IList<User>));
    }
}

It's failing on repository GetAll() method as null reference. I don't known what is missing.

Views: 7865
Total Answered: 2
Total Marked As Answer: 2
Posted On: 05-Jun-2020 20:43

Share:   fb twitter linkedin
Answers
mk
mk
30 Points
0 Posts
         

You are missing mock setup. You can do something:

var user = new List<User>();
//populate with dummy user data
_userRepository.Setup(p => p.GetAll()).Returns(users);
Posted On: 08-Jun-2020 06:23
beginer
beginer
1544 Points
52 Posts
         

You can try following:

public class Tests
{
    private Mock<IUserRepository> _userRepository;
    private IService _service;

    [SetUp]
    public void Setup()
    {
        _userRepository = new Mock<IUserRepository>();
        _service = new Service(_userRepository.Oject);
    }

    [Test]
    public void ShouldReturnUsers()
    {
        var users = new List<User>(){
          //populate with dummy user data
        };

        _userRepository.Setup(p => p.GetAll()).Returns(users);

        var result = _service.GetAllUser();

        Assert.That(() => result, Is.TypeOf(IList<User>));
    }
}
Posted On: 09-Jun-2020 06:22
Thanks. Helps a lot!
 - Rashmi  25-Oct-2023 22:31
 Log In to Chat