C# 无法正确模拟方法
我有下面的类,我正在尝试测试它的SaveEmployee方法C# 无法正确模拟方法,c#,unit-testing,moq,C#,Unit Testing,Moq,我有下面的类,我正在尝试测试它的SaveEmployee方法 public class EmployeeService : IEmployeeService { private readonly IRepository _repository; private readonly ISomeOtherService _someOtherService; public EmployeeService(IRepository repository, ISomeOtherService so
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
}
}
}
公共类EmployeeService:ieemployeeservice
{
专用只读IRepository存储库;
私有只读其他服务_someOtherService;
公共雇员服务(IRepository存储库、ISomeOtherService someOtherService)
{
_存储库=存储库;
_someOtherService=someOtherService;
}
公共雇员结果保存雇员(雇员协会雇员协会)
{
Employee newEmp=新员工()
{
Id=Guid.NewGuid(),
年龄=员工总年龄,
Name=员工助理姓名,
地址=员工助理地址
}
int saveReturnValue=_repository.Insert(newEmp);
if(saveReturnValue==1)
{
//在这里做点什么
}
其他的
{
//消息,保存不成功
}
}
}
下面是我创建的单元测试类
[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);
}
}
[TestClass]
公共类EmployeeCreateTest
{
模拟存储库;
模拟其他服务
员工服务
[测试方法]
public void SaveEmployee_executesuccessfully()
{
_repository=newmock();
_someOtherService=newmock();
_employeeService=newemployeeservice(_repository.Object,_someOtherService.Object);
员工emp=新员工();
_Setup(x=>x.Insert(emp)).Returns(1);
_employeeService.SaveEmployee(newemployeeassociation());
_验证(x=>x.Insert(emp),次,一次);
}
}
它总是给我下面的错误,
预期对模拟调用一次,但调用次数为0次
任何想法,我在做什么?执行SaveEmployee方法时的员工和验证的员工不相同。所以您只调用了一次Insert方法,但没有对该员工调用。因此,您在模拟中得到了一次预期调用,但得到了0次。因为SaveEmployee方法根据您的逻辑创建新员工
您可以尝试以下方法进行验证:
_repository.Verify(x => x.Insert<Employee>(It.IsAny<Employee>()), Times.Once);
\u repository.Verify(x=>x.Insert(It.IsAny()),Times.one);
这将验证您是否对任何员工调用了Insert方法