jeudi 24 septembre 2015

Unit Testing - updating model

I am new to unit testing and I am trying to write a test to verify that when I update my user object the correct fields are being updated. My unit test looks like:

[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));
}    

My repository looks like:

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();
}

The problem is when I get to Context.Entry(dbEmployee).CurrentValues.SetValues(employee); in my repository I get the following error: 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>.

Any help would be appreciated!

Aucun commentaire:

Enregistrer un commentaire