繁体   English   中英

单元测试 - 更新模型

[英]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>. 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>.

任何帮助,将不胜感激!

根据这篇文章 ,你应该改变:

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

至:

Context.Employees.Attach(employee)

然后你应该改变你的断言以验证使用employeeToUpdate调用Attach方法。(你在方法ReturnsDbSet隐藏了DBSet<> ,所以我无法添加一个例子......)

还有一件事,我想你应该看看这段代码片段 ,它显示了使用Moq模拟DBContextDBSet<>的正确方法。 或者阅读这篇文章

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM