用于检索已创建对象的单元测试

时间:2015-09-23 16:01:54

标签: unit-testing nunit moq

我是单元测试的新手,我正在尝试创建一个测试,以确保我可以检索已创建的用户。当我运行测试时,出现Expected invocation on the mock once, but was 0 times: m => m.Add(It.IsAny<Employee>()). No setups configured错误。 (错误发生在mockSet.Verify(...);

[Test]
public void ShouldRetrieveCreatedUser()
{
    var mockSet = new Mock<DbSet<Employee>>();

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

    var sut = new EmployeeRepository(mockContext.Object);

    var employeeToSave = new Employee
    {
        FirstName = "John",
        LastName = "Smith",
        Email = "John.Smith@gmail.com",
        IsActive = true,
        DateCreated = DateTime.Now,
        CreatedBy = "System",
        DateUpdated = DateTime.Now,
        UpdatedBy = "System"
    };

    sut.Save(employeeToSave);

    mockSet.Verify(m => m.Add(It.IsAny<Employee>()), Times.Once());
    mockContext.Verify(m => m.SaveChanges(), Times.Once());
}

我的存储库看起来像:

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.Employees.Add(employee)所以我不确定为什么当我验证它时它说它没有被调用。

0 个答案:

没有答案