我有一小组单元测试工作正常,直到我添加一个测试验证我的唯一约束是否正常工作。这些不是单元测试,而是集成测试。
无论如何,如果我省略了验证唯一约束的测试,那么删除的一切都很好。但是,如果我添加SerialNumberUniqueConstraint_Test方法,它会失败,我的item类不为null,因为删除永远不会发生。如果我在其他测试之前移动SerialNumberUniqueConstraint_Test,则后续测试也会失败并返回相同的UniqueFieldValueConstraintValidationException。我做错了什么?
[TestMethod]
[ExpectedException( typeof( UniqueFieldValueConstraintViolationException ) )]
public void SerialNumberUniqueConstraint_Test()
{
using( var logic = new ItemLogic() )
{
logic.Save( CreateItem() );
}
}
[TestMethod]
public void DeleteItem_Test()
{
Item item = null;
using( var logic = new ItemLogic() )
{
logic.Delete( SerialNumber );
}
using( var logic = new ItemLogic() )
{
item = logic.Retrieve( SerialNumber );
}
Assert.IsNull( item );
}
private Item CreateItem()
{
return new Item { Name = "My item", Make = "make", Model = "model", SerialNumber = "1234" };
}
public Item Save( Item item )
{
Db4oDatabase.Database.Store( item );
Db4oDatabase.Database.Commit();
return this.Retrieve( item.SerialNumber );
}
public Item Retrieve( string serialNumber )
{
Item item = (from i in Db4oDatabase.Database.AsQueryable<Item>()
where i.SerialNumber == serialNumber
select i).FirstOrDefault();
return item;
}
public void Delete( string serialNumber )
{
Db4oDatabase.Database.Delete( this.Retrieve( serialNumber ) );
}
答案 0 :(得分:1)
数据类'Save方法现在在Commit()操作上使用try / catch,并在发生UniqueFieldValueConstraintViolationException时执行回滚。另外,我根据Bob Horn的建议使DeleteItem_Test独立。
public Item Save( Item item )
{
Db4oDatabase.Database.Store( item );
try
{
Db4oDatabase.Database.Commit();
}
catch( UniqueFieldValueConstraintViolationException )
{
Db4oDatabase.Database.Rollback();
throw;
}
return this.Retrieve( item.SerialNumber );
}
[TestMethod]
public void DeleteItem_Test()
{
string serialNumber = "DeleteItem_Test";
Item item = new Item
{
Name = "Washer",
Make = "Samsung",
Model = "Model No",
SerialNumber = serialNumber,
PurchasePrice = 2500m
};
using( var logic = new ItemLogic() )
{
item = logic.Save( item );
Assert.IsNotNull( item, TestResources.DevMessage_IntermediateOperationFailed, "Save", serialNumber );
logic.Delete( item );
item = logic.Retrieve( serialNumber );
}
Assert.IsNull( item );
}