2011-03-09 56 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

相关问题