我應該在我的域對象中測試數據庫約束嗎?例如。如果數據庫中的字段是varchar(500)並且是必需的,我應該在代碼中對此進行測試嗎?或者我應該只依靠一個try/catch。TDD - 我應該在我的域模型中測試數據庫約束嗎?
這是一個相當大的工作開銷 - 如果可以避免的話。有例外的規則打交道時
即
//partial method for a class generated by the Entity framework
[MetadataType(typeof(UserMetaData))]
public partial class User
{
}
public class UserMetaData
{
[Required]
[StringLength(500)]
public string FirstName { get; set; }
}
// My domain object tests
// This test in particular will throw an expected exception, saying that the first name cannot be found
[TestFixture]
public class UserTest
{
[Test]
[ExpectedException(typeof(ValidationException), ExpectedMessage = "The FirstName field is required.")]
public void user_should_require_first_name()
{
User user = new User();
user.Id = 0;
user.MiddleName = "x";
user.IsAdmin = true;
user.LastName = "James";
user.Password = "password";
user.Title = "Mr";
user.Username = "jamesbrown";
user.Email = "[email protected]";
TestsHelper.ValidateObject(user);
}
}
丹尼爾 - 這是你在你的軟件中做的事嗎?例如。編寫測試來驗證你的ViewModel的字符串長度和所需的等等? – 2011-03-10 16:17:22
@ Sebastian Patten:只有當約束可能被擊中,我不希望用戶看到數據庫異常。但我只是這樣做,因爲我很懶;-)我認爲將所有約束放入ViewModel會更好 – 2011-03-10 16:28:33