C#-单元测试-更新模型
作者:互联网
我是单元测试的新手,我试图编写一个测试来验证在更新用户对象时是否正在更新正确的字段.我的单元测试如下:
[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);在我的存储库中,出现以下错误:无法为类型为’Employee’的实体调用成员’CurrentValues’,因为该实体在上下文中不存在.要将实体添加到上下文,请调用DbSet< Employee>的Add或Attach方法.
任何帮助,将不胜感激!
解决方法:
基于this article,您应该更改:
Employee dbEmployee = Context.Employees.Find(employee.EmployeeId);
Context.Entry(dbEmployee).CurrentValues.SetValues(employee);
至:
Context.Employees.Attach(employee)
然后,您应该更改断言以验证是否使用employeeToUpdate调用了Attach方法.(您将DBSet<>隐藏在ReturnDbSet方法中,因此我无法添加示例…)
还有一件事,我认为您应该看一下this code snippet,它显示了模拟DBContext和DBSet<>的正确方法.使用起订量.或read this article
标签:unit-testing,nunit,moq,c,entity-framework 来源: https://codeday.me/bug/20191119/2038024.html