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?

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;
}