使用Moq模拟存储库

时间:2014-07-11 05:52:04

标签: c# unit-testing mocking repository moq

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

你知道我错过了吗?

谢谢,

[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);
    }
}

1 个答案:

答案 0 :(得分:3)

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

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

模拟是虚假对象,它在方法中没有任何逻辑。您必须告诉它它应该如何表现(设置),以便在您的测试中可以重播此行为。