TDD - 我应该在我的域模型上测试数据库约束吗?
我应该在域对象中测试数据库约束吗?例如,如果数据库中的字段是 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 = "[email protected]";
TestsHelper.ValidateObject(user);
}
}
Should I test database constraints in my domain object? E.g. If the field in the database is varchar(500) and required, should I have a test for this in my code? Or should I just rely on a try/catch.
It is a fairly large overhead of work to do - if it can be avoided.
I.e
//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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,在处理规则的异常时,try...catch 是最有效的。这也意味着您只需要在数据库中更改/添加规则 - 而不是在数据库和代码中。
In general try...catch is the most efficient when dealing with exceptions to a rule. It also means you only need to change/add a rule in the DB - not in the DB and the code.
恕我直言,域模型是进行此类检查的错误位置。如果您想向用户提供比数据库中的异常文本更有意义的错误消息,请将输入值验证添加到您的 UI 层(即 ViewModel 或 Controller)。
IMHO, the domain model is the wrong place to do checks like this. If you want to provide the user with a more meaningful error message than the exception text from the database, add validation of input values to your UI layer, i.e. your ViewModel or Controller.