gpt4 book ai didi

c# - 单元测试 - 更新模型

转载 作者:行者123 更新时间:2023-11-30 16:06:06 26 4
gpt4 key购买 nike

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

[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 调用方法.(你在方法 DBSet<> 中隐藏了 ReturnsDbSet 所以我无法添加示例...)

还有一件事,我觉得你应该看看this code snippet这显示了模拟 DBContext 的正确方法和 DBSet<>使用 Moq .或者 read this article

关于c# - 单元测试 - 更新模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32761500/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com