1

I am using DataAnnotations for my model validation

using System.ComponentModel.DataAnnotations;

namespace MvcApplication2.Models
{
    public class Fiz
    {
        [Required]
        public string Name { get; set; }

        [Required]
        [RegularExpression(".+@..+")]
        public string Email { get; set; }

        [Required]
        public string adress { get; set; }

        [Required]
        public string city { get; set; }

        [Required]
        public string gold { get; set; }

        [Required]
        public string father { get; set; }
    }
}

// test class
[TestMethod]
public void EmailRequired()
{
    var fiz = new Fiz 
    {

        Email = "exemple"
    };

    Assert.IsTrue(ValidateModel(fiz).Count > 0);
}

private IList<ValidationResult> ValidateModel(object model)
{
    var validationResults = new List<ValidationResult>();
    var ctx = new ValidationContext(model, null, null);
    Validator.TryValidateObject(model, ctx, validationResults, true);
    return validationResults;
}

the problem that i want to test just the Email but in this case i have to give a values to fiz.Name;fiz.adress;.....

any solutions? thinks

2 Answers 2

1

Check out AutoFixture

https://github.com/AutoFixture

It can hydrate your entities with data, so you only have to concern yourself with the properties that you want to test.

Great for creating your test entities in just a few lines of code

Sign up to request clarification or add additional context in comments.

2 Comments

can you give me an exemple or a tutorial about that ?!
nikosbaxevanis.com/blog/2011/02/22/… shows the basics, it is really easy though.
0

If you really want to test that your data annotations are correctly placed, you need to provide data to every field (either manually or with some 3rd party tool). But hits might not be such a bad idea as you can create one test per entire object and assert on the contents of the validationResults;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.