I would like to test my controller method for a given MyModelDTO
values.
This is my controller Post method (simplified):
[HttpPost]
public ActionResult Post([FromBody] MyModelDTO itemDTO)
{
ModelState.Remove($"{nameof(itemDTO)}.{nameof(itemDTO.Id)}");
if (!ModelState.IsValid)
{
return BadRequest();
}
//rest of code
}
My MyModelDTO
class:
public class MyModelDTO
{
[IsNotEmpty(ErrorMessage = "Guid Id Is Empty")]
public Guid Id { get; set; }
}
My custom ValidationAttribute
:
public class IsNotEmptyAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null) return false;
var valueType = value.GetType();
var emptyField = valueType.GetField("Empty");
if (emptyField == null) return true;
var emptyValue = emptyField.GetValue(null);
return !value.Equals(emptyValue);
}
}
My question is how to test the automatic validation for the ModelState's custom attribute?
This is what I've tried:
[Test] public void Post_WhenCalled_ShouldReturnPostResult()
{
using (var mock = AutoMock.GetLoose())
{
//Arrange
var controller = mock.Create<MyController>();
//Act
ActionResult actionResult = controller.Post(new MyModelDTO());
//Assert...
}
}
The unit test works OK (the controller should work with a parameter MyModelDTO
with no Id
), but it looks like it does not really mocking the automatic validation process of ModelState. How do I know this? because when I try to do a postman with body missing of Id
property it result with "Guid Id Is Empty"
message. it won't even stop at the breakpoint.