无法正确模拟方法

not able to mock a method correctly

我有以下 class,我正在尝试测试它的 SaveEmployee 方法。

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

下面是我创建的单元测试class

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

它总是给我下面的错误, 预期对模拟调用一次,但为 0 次 ...

任何想法,我在做什么错?

你执行SaveEmployee方法时的Employee和你验证的Employee不一样。因此,您调用了一次 Insert 方法,但没有与该员工一起调用。所以你得到了一次 Expected invocation on the mock,但是是 0 次。因为你的 SaveEmployee 方法按照你的逻辑创建了一个新的 Employee。


您可以尝试以下方法验证,

 _repository.Verify(x => x.Insert<Employee>(It.IsAny<Employee>()), Times.Once);

这证明您对任何员工调用了 Insert 方法