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_sh开发者_开发问答ould_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);
}
}
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.
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.
精彩评论