I have a Dto class ContactInformationDto which contains the fields Phonenumber and Emailaddress. In my endpoint I want to use ModelState.IsValid to check whether both fields meet the requirements I have set.
The ContactInformationDto looks like this:
public class ContactInformationDto
{
[Required(ErrorMessage = "Phonenumber is required")]
[MaxLength(15, ErrorMessage = "Phonenumber is too long")]
public string Phonenumber { get; set; }
[Required(ErrorMessage = "Emailaddress is required")]
public string Emailaddress { get; set; }
}
My endpoint:
[HttpPost]
public async Task<IActionResult> SaveContactInformation([FromBody] ContactInformationDto contactInformation, CancellationToken cancelllationToken)
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
}
When I run the following unit test ModelState.IsValid is always true and the test fails.
public async Task SaveContactInformation_IfNoPhoneNumber_ThenBadRequest()
{
var contactInformation = new ContactInformationDto
{
Emailaddress = "[email protected]"
}
var actionResult = await _controller.SaveContactInformation(contactInformation, _cancellationToken);
Assert.IsBadRequest(actionResult);
}
My other test with a Phonenumber longer than the allowed number of characters alse fails.
---- Solution ----
@Xerillio points out correctly that modelstate validation does not happen in the unit test I'm using here.
I added an error in my unit test to the modelstate to test how my method reacts to Model.IsValid and an integration test to test if my validation attributes are correct.