mercredi 30 septembre 2015

Unit Testing Insert Empty Record Should Throw Error

I am new to unit testing and I am trying to test that a new Employee record should not be inserted into the database. When I call Context.SaveChanges() it does not throw the error in the unit test, but when I try it out in the Controller it throws an error like expected.

I am guessing that the Employee entity isn't being added to the context in the unit test so when I call SaveChanges() nothing is actually being saved? Any help would be appreciated!

Unit Test

[Test]
[ExpectedException(typeof(DbEntityValidationException))]
public void ShouldNotSaveEmptyEmployee()
{
    var mockSet = new Mock<DbSet<Employee>>();

    var mockContext = new Mock<SqlContext>();
    mockContext.Setup(m => m.Employees).Returns(mockSet.Object);

    var sut = new EmployeeRepository(mockContext.Object);
    sut.Save(new Employee());
}

Repository:

public void Save(Employee employee)
{
    if (employee.EmployeeId > 0)
    {
        Context.Entry(employee).State = EntityState.Modified;
    }
    else
    {
        Context.Employees.Add(employee);
    }

    Context.SaveChanges();
}

Aucun commentaire:

Enregistrer un commentaire