0

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

        TestsHelper.ValidateObject(user);
    }
}
tereško
  • 58,060
  • 25
  • 98
  • 150
Sebastian Patten
  • 7,157
  • 4
  • 45
  • 51

2 Answers2

0

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.

SpliFF
  • 38,186
  • 16
  • 91
  • 120
0

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.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • Daniel - is this something you do in your software? E.g. Write tests to validate string length, and required etc for your ViewModel? – Sebastian Patten Mar 10 '11 at 16:17
  • @Sebastian Patten: Only if the constraint is likely to be hit and I don't want the user to see the database exception. But I am doing it this way only, because I am lazy ;-) I think it would be better to put all constraints into the ViewModel – Daniel Hilgarth Mar 10 '11 at 16:28