Reputation: 319
I have below class, and I am trying to test its SaveEmployee method.
public class EmployeeService : IEmployeeService
{
private readonly IRepository _repository;
private readonly ISomeOtherService _someOtherService;
public EmployeeService(IRepository repository, ISomeOtherService someOtherService)
{
_repository = repository;
_someOtherService = someOtherService;
}
public EmployeeResult SaveEmployee(EmployeeAssociation employeeAssoc)
{
Employee newEmp = new Employee()
{
Id = Guid.NewGuid(),
Age = employeeAssoc.Age,
Name = employeeAssoc.Name,
Adress = employeeAssoc.Address
}
int saveReturnValue = _repository.Insert<Employee>(newEmp);
if (saveReturnValue == 1)
{
// Do something here
}
else
{
// message, save not successful
}
}
}
Below is the unit test class I have created
[TestClass]
public class EmployeeCreateTest
{
Mock<IRepository> _repository;
Mock<ISomeOtherService> _someOtherService
IEmployeeService _employeeService
[TestMethod]
public void SaveEmployee_ExecutesSuccessfully()
{
_repository = new Mock<IRepository>();
_someOtherService = new Mock<ISomeOtherService>();
_employeeService = new EmployeeService(_repository.Object, _someOtherService.Object);
Employee emp = new Employee();
_repository.Setup(x => x.Insert<Employee>(emp)).Returns(1);
_employeeService.SaveEmployee(new EmployeeAssociation());
_repository.Verify(x => x.Insert<Employee>(emp), Times.Once);
}
}
It always gives me below error, Expected invocation on the mock once, but was 0 times ...
Any ideas, what's wrong I am doing?
Upvotes: 2
Views: 247
Reputation: 1416
The Employee when you execute SaveEmployee method and the Employee where you verify are not the same. So you called Insert method once but not with this employee. So you get Expected invocation on the mock once, but was 0 times. Because your SaveEmployee method creates a new Employee according to your logic.
You can try the following to verify,
_repository.Verify(x => x.Insert<Employee>(It.IsAny<Employee>()), Times.Once);
This verifies that you called Insert method with any employee
Upvotes: 4