2011-03-09 55 views
0

我應該在我的域對象中測試數據庫約束嗎?例如。如果數據庫中的字段是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); 
    } 
} 

回答

0

一般TRY ... CATCH是最有效的。這也意味着您只需要在數據庫中更改/添加規則 - 而不是在數據庫和代碼中。

0

恕我直言,域模型是做錯檢查這樣的地方。如果要爲用戶提供比數據庫中的異常文本更有意義的錯誤消息,請將輸入值驗證添加到UI層(即ViewModel或Controller)。

+0

丹尼爾 - 這是你在你的軟件中做的事嗎?例如。編寫測試來驗證你的ViewModel的字符串長度和所需的等等? – 2011-03-10 16:17:22

+0

@ Sebastian Patten:只有當約束可能被擊中,我不希望用戶看到數據庫異常。但我只是這樣做,因爲我很懶;-)我認爲將所有約束放入ViewModel會更好 – 2011-03-10 16:28:33

相關問題