编程语言
首页 > 编程语言> > c#-Moq工作单元

c#-Moq工作单元

作者:互联网

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

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.我收到一个空引用异常.我如何起订UnitOfWork,以便可以测试搜索是否返回了正确的员工数量.

解决方法:

为了模拟存储库,最简单的为其创建一个接口,例如IEmployeeRepo.然后,在EmployeeService类中,该字段将为私有只读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.");  

标签:unit-testing,nunit,moq,c
来源: https://codeday.me/bug/20191119/2037645.html