Search code examples
asp.net-mvcunit-testingasp.net-mvc-5fakeiteasyvalidationattribute

How to fake ValidationContext using FakeItEasy?


I have one class which is derived from ValidationAttribute (of DataAnnotation in MVC)

Following is the overridden method of this class:

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null)
            return ValidationResult.Success;

        var tagWithoutClosingRegex = new Regex(@"<[^>]+>");

        var hasTags = tagWithoutClosingRegex.IsMatch(value.ToString());

        if (!hasTags)
            return ValidationResult.Success;

        return new ValidationResult(String.Format("{0} cannot contain html tags", validationContext.DisplayName));
    }

I want to write unit tests for this method. How can I fake ValidationContext using FakeItEasy to make this testable?

Any help on this much appreciated

Thanks


Solution

  • In general, it's good practise to tell us what kind of things you've tried, and what has or hasn't worked, and how. That will likely get you better (and quicker) answers in the future. See How to ask for more pointers.

    However, I can help a little.

    ValidationContext is sealed and so it cannot be faked. See What can be faked for more information about what kinds of types can and cannot be faked.

    I'm not familiar with the ValidationContext. Is it possible that you don't need to fake one, that you can just create one and provide it with state that will serve your tests?