工作单位起订 [英] Moq Unit of Work
问题描述
我是新来的单元测试,我想创建我的搜索功能的测试。我的服务层看起来是这样的:
I am new to unit testing and I want to create a test for my search feature. My service layer looks something like:
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);
}
}
单元测试:
Unit Test:
[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
。我得到一个空引用异常
。我怎样才能起订量的的UnitOfWork
这样我就可以测试正在从搜索返回的员工正确的号码。
I think the issue is with mocking the UnitOfWork
. I am getting a Null Reference Exception
. How can I moq the UnitOfWork
so I can test that the correct number of employees is being returned from the Search.
推荐答案
有关嘲讽库这将是最简单的创建一个接口为它,例如: IEmployeeRepo
。然后在的EmployeeService
类领域将是私人只读IEmployeeRepo _employeeRepo
。
For mocking the repository it would be the easiest to create an interface for it, e.g. IEmployeeRepo
. Then in the EmployeeService
class the field would be private readonly IEmployeeRepo _employeeRepo
.
在测试然后你可以验证搜索
被调用。
In the test you could then verify that Search
was called.
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.");
这篇关于工作单位起订的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!