Moq Unit of Work

社会主义新天地 提交于 2019-12-06 03:09:36

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