我在单元测试中使用事务来回滚更改.单元测试使用dbcontext,我正在测试的服务使用自己的.它们都包装在一个事务中,一个dbcontext在另一个事务的块中.问题是,当内部dbcontext保存他的更改时,外部dbcontext不可见(我不认为这是因为另一个dbcontext可能已经加载了对象).这是一个例子:
[TestMethod]
public void EditDepartmentTest()
{
using (TransactionScope transaction = new TransactionScope())
{
using (MyDbContext db = new MyDbContext())
{
//Arrange
int departmentId = (from d in db.Departments
where d.Name == "Dep1"
select d.Id).Single();
string newName = "newName",
newCode = "newCode";
//Act
IDepartmentService service = new DepartmentService();
service.EditDepartment(departmentId, newName, newCode);
//Assert
Department department = db.Departments.Find(departmentId);
Assert.AreEqual(newName, department.Name,"Unexpected department name!");
//Exception is thrown because department.Name is "Dep1" instead of "newName"
Assert.AreEqual(newCode, department.Code, "Unexpected department code!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
服务:
public class …Run Code Online (Sandbox Code Playgroud)