0

我应该在我的域对象中测试数据库约束吗?例如,如果数据库中的字段是 varchar(500) 并且是必需的,我是否应该在我的代码中对此进行测试?或者我应该只依靠try/catch。

这是一个相当大的工作开销——如果可以避免的话。

IE

//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 = "jamesbrown@somewebsite.com";

        TestsHelper.ValidateObject(user);
    }
}
4

2 回答 2

0

一般来说,try...catch 在处理规则的异常时是最有效的。这也意味着您只需要在数据库中更改/添加规则 - 而不是在数据库和代码中。

于 2011-03-10T00:10:05.200 回答
0

恕我直言,域模型是进行此类检查的错误位置。如果您想为用户提供比数据库中的异常文本更有意义的错误消息,请将输入值验证添加到您的 UI 层,即您的 ViewModel 或 Controller。

于 2011-03-10T07:47:18.547 回答