最小工作量单位

本文关键字:单位 工作量 | 更新日期: 2023-09-27 18:16:03

我是单元测试的新手,我想为我的搜索功能创建一个测试。我的服务层看起来像这样:

public class EmployeeService: BaseService, IEmployeeService
{
    public EmployeeService(IUnitOfWork unitOfWork) : base(unitOfWork)
    {
        _employeeRepo = unitOfWork.EmployeeRepository;
    }
    public IEnumerable<Employee> Search(Employee advancedSearch, int[] divisionIds, bool showInactive, int pageSize, int? page)
    {
        return _employeeRepo.Search(advancedSearch, divisionIds, showInactive, pageSize, page);
    }
}
单元测试:

[Test]
public void SearchShouldFilterActiveEmployees()
{
    var employees = new List<Employee>
    {
        new Employee { EmployeeId = 105, FirstName = "John", LastName = "Smith", IsActive = true },
        new Employee { EmployeeId = 162, FirstName = "John", LastName = "Doe", IsActive = true },
        new Employee { EmployeeId = 3, FirstName = "Jan", LastName = "Doe", IsActive = true }
    };
    var mockUnitOfWork = new Mock<IUnitOfWork>();
    var sut = new EmployeeService(mockUnitOfWork.Object);
    var employeeSearchCriteria = new Employee
    {
        FirstName = "John"
    };
    var employeesReturned = sut.Search(employeeSearchCriteria, null, false, 25, 1);
    Assert.IsTrue(employeesReturned.Count() == 2);
}

我认为问题是嘲笑UnitOfWork。我得到一个Null Reference Exception

最小工作量单位

如何修改UnitOfWork,以便我可以测试从搜索中返回的员工的正确数量。

要模拟存储库,最简单的方法是为它创建一个接口,例如IEmployeeRepo。那么在EmployeeService类中,字段将是private readonly IEmployeeRepo _employeeRepo

在测试中,您可以验证是否调用了Search
bool searchwasCalled = false;
Mock<IEmployeeRepo> repositoryMock = new Mock<IEmployeeRepo>();
repositoryMock.Setup(r => r.Search(
    It.IsAny<Employee>(), It.IsAny<int[]>(), It.IsAny<bool>(), It.IsAny<int>(),
    It.IsAny<int?>()))
    .Callback(() => searchwasCalled = true);
var mockUnitOfWork = new Mock<IUnitOfWork>();
mockUnitOfWork.Setup(uow => uow.EmployeeRepository).Returns(repositoryMock.Object);
var sut = new EmployeeService(mockUnitOfWork.Object);
var employeeSearchCriteria = new Employee
{
    FirstName = "John"
};
sut.Search(employeeSearchCriteria, null, false, 25, 1);
Assert.IsTrue(searchwasCalled, "Search was not called.");