gpt4 book ai didi

c# - 最小起订量工作单位

转载 作者:行者123 更新时间:2023-11-30 16:05:55 27 4
gpt4 key购买 nike

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

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 以便我可以测试是否从搜索中返回了正确数量的员工。

最佳答案

为了模拟存储库,最简单的方法是为它创建一个接口(interface),例如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.");

关于c# - 最小起订量工作单位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32956212/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com