I am writing a unit test for a controller like this:
public HttpResponseMessage PostLogin(LoginModel model)
{
if (!ModelState.IsValid)
return new
I used the following to validate the model state in unit test Visual studio 2017, C#, NET 4.x.x
[TestMethod]
public void TestYourValidationModel()
{
var configuration = new HttpConfiguration();
configuration.Filters.Add(new ValidateModelAttribute());
// Get the quote
var controller = new YourController
{
Request = new HttpRequestMessage(),
Configuration = configuration
};
var request = YourRequestObject;
controller.Request.Content = new ObjectContent(
request, new JsonMediaTypeFormatter(), "application/json");
controller.Validate(request);
Assert.IsTrue(controller.ModelState.IsValid, "This must be valid");
}
The example is for a request in JSON format. Substitute YourController for the name of your controller, and YourRequesType, for the object type of your request.
This give you the option to test your model for validation without go to the service.