2

I was trying to do unit testing for validations on c# models using Validator but it is not working with NewtonSoft attributes.

Here's my unit test:

var searchController = new SearchController();
var requestModel = new RequestModel
{
   Id = "23456",
   MobileNumber = "9876543210"
};

var results = new List<ValidationResult>();
var context = new ValidationContext(requestModel, null, null);
var isvalid = Validator.TryValidateObject(requestModel, context, results,true);
Assert.IsFalse(isvalid);

And here's my model:

public class XYZ
{
    [JsonProperty("mobileNumber")]
    [MinLength(3, ErrorMessage = "MOBILENUMBER_LENGTH_MIN")]
    public string MobileNumber { get; set; }

    [JsonProperty("refNumber")]
    [MinLength(3, ErrorMessage = "REFNUMBER_LENGTH_MIN")]
    public string RefNumber { get; set; }

    [JsonProperty("subscriberFirstName")]
    [MinLength(3, ErrorMessage = "FIRSTNAME_LENGTH_MIN")]
    public string FirstName { get; set; }
}

Can someone help me with this?

2
  • It throws an exception or it doesn't work as expected? Commented Dec 3, 2015 at 10:19
  • It doesn't work as expected. But when i remove JsonProperty attribute from models, then it works perfectly. Commented Dec 3, 2015 at 11:52

1 Answer 1

0

Adapted Jon Davis's answer on Unit Testing ASP.NET DataAnnotations validation

If you have a class like this:

public class Person
{
  [MinLength(3, ErrorMessage = "FIRSTNAME_LENGTH_MIN")]
  public string FirstName { get; set; }

  [MinLength(3, ErrorMessage = "MOBILENUMBER_LENGTH_MIN")]
  public string MobileNumber { get; set; }
}

You can test the validation results like this:

[TestMethod]
public void ModelValidationFailsWithInvalidLength()
{
  // arrange
  var myPerson = new Person()
  {
    FirstName = "Hi",
    MobileNumber = "12"
  };

  // act
  var validationResults = ValidateModel(myPerson);

  // assert
  Assert.IsTrue(validationResults.Any(
    v => v.MemberNames.Contains(nameof(Person.FirstName)) &&
         v.ErrorMessage.Contains("FIRSTNAME_LENGTH_MIN")));
}

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;
}
Sign up to request clarification or add additional context in comments.

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.