-3

我的测试用例总是失败,告诉我哪里错了,代码如下

public class EmployeeService
{
    private readonly IRepository _repository;

    public EmployeeService(IRepository repository)
    {
        _repository = repository;
    }

    public bool SaveEmployeeData(Employee employee,bool isSaveNeeded)
    {
        bool result = false;
        try
        {
            if (isSaveNeeded)
            {
                result= _repository.Save(employee);
            }
        }
        catch (Exception ex)
        {
            throw new Exception();
        }
        return result;
    }
}

我的测试用例是

[TestMethod()]
public void SaveEmployeeDataTest()
{
    var a = new Mock<IRepository>();
    a.Setup(s => s.Save(new Employee())).Returns(true).Verifiable();
    var result = new EmployeeService(a.Object).SaveEmployeeData(new Employee(), true);
    Assert.IsTrue(result);
}

它总是失败。

4

3 回答 3

4

用于It.IsAny<Employee>设置保存方法参数

a.Setup(s => s.Save(It.IsAny<Employee>())).Returns(true).Verifiable();

您的测试不起作用的原因是因为您有两个不同的员工实例 - 一个用于模拟设置,一个用于传递给SaveEmployeeData方法调用。默认情况下,这些实例将通过引用进行比较。Moq 等待Save带有引用 13(例如)的员工实例的方法调用。但是您通过引用 42 传递了另一个员工。因此永远不会调用 setup。

你还有两个选择

  • 类的覆盖EqualsGetHashCode方法Employee。因此,起订量将不会通过参考来比较员工,而是通过业务数据。
  • 使用完全相同的员工实例进行模拟设置和SaveEmployeeData方法调用(首选方式)

相同员工实例的用法:

[TestMethod()]
public void SaveEmployeeDataTest()
{
    var a = new Mock<IRepository>();
    var sameEmployee = new Employee();
    a.Setup(s => s.Save(sameEmployee)).Returns(true).Verifiable();

    var service = new EmployeeService(a.Object);
    var result = service.SaveEmployeeData(sameEmployee, true);
    Assert.IsTrue(result);
}

压倒一切的平等:

public class Employee
{
    public override bool Equals(object obj)
    {
        Employee other = obj as Employee;
        if (other == null)
            return false;

        return this.Id == other.Id; // for example
    }
}

在这种情况下,您可以保持测试不变。

于 2013-06-26T13:04:53.800 回答
3

new Employee()每次都创建一个新的员工实例,一次用于设置,另一个Save用于实际设置SaveEmployeeData。因此,提供的员工永远不符合设置的要求。

要么使用像lazyberezovsky's answer这样的包罗万象的方法,要么执行以下操作:

[TestMethod()]
public void SaveEmployeeDataTest()
{
    var a = new Mock<IRepository>();
    var employee = new Employee();
    a.Setup(s => s.Save(employee)).Returns(true).Verifiable();
    var result = new EmployeeService(a.Object).SaveEmployeeData(employee, true);
    Assert.IsTrue(result);
}

因为Employee设置中使用了与实际调用中相同的实例,所以设置匹配并返回正确的结果。

于 2013-06-26T13:05:49.123 回答
1

试试这个 -

[TestMethod()]
public void SaveEmployeeDataTest()
{
    var a = new Mock<IRepository>();
var employee = new Employee();
    a.Setup(s => s.Save(employee)).Returns(true).Verifiable();
    var result = new EmployeeService(a.Object).SaveEmployeeData(employee, true);
    Assert.IsTrue(result);
}

You need to use the same employee instance in setup as well as method call. This would ensure the verification that your are using the same employee instance which is passed in method and not something created in method or returned from another method.

于 2013-06-26T13:07:45.600 回答