使用 Moq 模拟存储库 [英] Mocking a repository with Moq

查看:48
本文介绍了使用 Moq 模拟存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了模拟存储库,我使用下面的代码.我不明白为什么变量 empl 总是 null.

To mock a repository, I use the code below. I don't understand why the variable empl is always null.

你知道我错过了什么吗?

Do you know what I missed ?

谢谢,

[TestMethod]
public void Test()
{
    var employee = new Employee { EmployeeID = 1, Code = "Code", FirstName = "MyFirstName", LastName = "MyName" };

    var employeeRepository = new Mock<IEmployeeRepository>();
    employeeRepository.Setup(x => x.Add(employee)).Verifiable();

    var employeeService = new EmployeeService(employeeRepository.Object);
    var empl = employeeService.GetById(1);

    Assert.IsNotNull(empl);
}

public class Employee
{
    public int EmployeeID { get; set; }
    public string Code { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public interface IEmployeeRepository : IBaseRepository<Employee> {}

public interface IBaseRepository<TEntity>
{
    IQueryable<TEntity> Get();
    TEntity Add(TEntity entity);
    void Delete(int id);
    int Count();
}

public class EmployeeService
{
    private IEmployeeRepository _employeeRepository;

    public EmployeeService(IEmployeeRepository employeeRepository)
    {
        _employeeRepository = employeeRepository;
    }

    public Employee GetById(int id)
    {
        return _employeeRepository.Get().FirstOrDefault(x => x.EmployeeID == id);
    }

    public void Add(Employee employee)
    {
        _employeeRepository.Add(employee);
    }
}

推荐答案

你在嘲笑错误的方法.模拟 Get:

You are mocking wrong method. Mock Get:

employeeRepository.Setup(x => x.Get()).Returns(new[] { employee });

Mock 是一个假对象,它在方法中没有任何逻辑.您必须告诉它它应该如何行为(设置),以便在您的测试中可以重播这种行为.

Mock is a fake object, it doesn't have any logic in methods. You have to tell it how exactly it should behave (setup) so that in your test this behavior can be replayed.

这篇关于使用 Moq 模拟存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆