How to mock repository in unit test .net core?

ykl
ykl
4 Points
2 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: 95
Total Answered: 2
Total Marked As Answer: 1
Posted On: 05-Jun-2020 20:43

Share:   fb twitter linkedin
Answers
mk
mk
2 Points
1 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
152 Points
46 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
 Log In to Chat