Closed michaelbowman1024-zz closed 7 years ago
You'll need to set controller.ObjectValidator
when trying to test anything that calls TryValidateModel
. I wonder if there's anything we can do to make this better.
Closing because this appears to be answered. If this doesn't help please reactivate or open a new issue
@rynowak I was just having the same issue. while search for answer land me on this page. even adding the code below solve the problem. But it does not feel right that we need to do that in order to use TryValidateModel for unit testing.
and this knowledge (or information) is not mentioned in the document of ControllerBase.TryValidateModel
It does not feel right because this piece of code is not within any of our testing logic. If we cannot improve upon this, we should at least mention this in the docs of TryValidateModel.
var objectValidator = new Mock<IObjectModelValidator>();
objectValidator.Setup(o => o.Validate(It.IsAny<ActionContext>(),
It.IsAny<ValidationStateDictionary>(),
It.IsAny<string>(),
It.IsAny<Object>()));
_sut.ObjectValidator = objectValidator.Object;
I have what seems to be a very similar issue to issue #3586, where TryValidateModel throws an Object reference error when unit tested. During normal operation with similar data being passed into the controller, the validation passes. Here is the controller method:
...and here is the unit test implementation:
As well as the Automapper CollectionDefinition:
The stack trace: