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.
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