单元测试 - 更新模型

Unit Testing - updating model

我是单元测试的新手,我正在尝试编写一个测试来验证当我更新我的用户对象时是否更新了正确的字段。我的单元测试看起来像:

[Test]
public void ShouldUpdateExistingEmployee()
{
    var employees = new Employee[]
    {
        new Employee()
        {
            EmployeeId = 1,
            FirstName = "Johhn",
            LastName = "Smiths",
            Email = "John.Smith1@Illinois.gov",
            IsActive = true
         }
    };

    var mockContext = new Mock<SqlContext>();
    mockContext.Setup(e => e.Employees).ReturnsDbSet(employees);
    mockContext.Setup(m => m.Employees.Find(It.IsAny<object[]>()))
         .Returns<object[]>(
                  ids => employees.FirstOrDefault(d => d.EmployeeId == (int)ids[0]));

    var sut = new EmployeeRepository(mockContext.Object);

    var employeeToUpdate = new Employee
    {
        EmployeeId = 1,
        FirstName = "John",
        LastName = "Smith",
        Email = "John.Smith@Illinois.gov",
        IsActive = true
    };

    sut.Save(employeeToUpdate);

    Assert.That(employees.First().FirstName, Is.EqualTo(employeeToUpdate.FirstName));
    Assert.That(employees.First().LastName, Is.EqualTo(employeeToUpdate.LastName));
    Assert.That(employees.First().Email, Is.EqualTo(employeeToUpdate.Email));
}    

我的存储库如下所示:

public void Save(Employee employee)
{
    if (employee.EmployeeId > 0)
    {
        Employee dbEmployee = Context.Employees.Find(employee.EmployeeId);
        Context.Entry(dbEmployee).CurrentValues.SetValues(employee);
    }
    else
    {
        Context.Employees.Add(employee);
    }

    Context.SaveChanges();
}

问题是当我到达我的存储库中的 Context.Entry(dbEmployee).CurrentValues.SetValues(employee); 时,我收到以下错误:Member 'CurrentValues' cannot be called for the entity of type 'Employee' because the entity does not exist in the context. To add an entity to the context call the Add or Attach method of DbSet<Employee>.

如有任何帮助,我们将不胜感激!

基于this article,你应该改变:

Employee dbEmployee = Context.Employees.Find(employee.EmployeeId);
Context.Entry(dbEmployee).CurrentValues.SetValues(employee);

至:

Context.Employees.Attach(employee)

然后你应该改变你的断言来验证 Attach 方法是用 employeeToUpdate 调用的。(你在方法 ReturnsDbSet 中隐藏了 DBSet<> 所以我不能'添加示例...)

还有一件事,我想你应该看看 this code snippet which shows the right way to mock DBContext and DBSet<> using Moq. Or read this article