Moq Unit of Work

风格不统一 提交于 2019-12-07 12:50:15

问题


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

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.


回答1:


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.");  


来源:https://stackoverflow.com/questions/32956212/moq-unit-of-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!