Testing request model validation

As mentioned, the FluentValidation package provides an excellent way to test our validation criteria.

The AddItemRequestValidator and EditItemRequestValidator classes implement elementary checks. Furthermore, it may be useful to cover them with some tests to document the logic implemented in these classes. FluentValidation provides a TestHelper class that provides the assertion conditions necessary to verify the behavior of our validation logic.

Let's see how to do some unit tests for the AddItemRequestValidator class:

using Catalog.Domain.Entities;
using Catalog.Domain.Requests.Item;
using Catalog.Domain.Requests.Item.Validators;
using FluentValidation.TestHelper;
using Xunit;

namespace Catalog.Domain.Tests.Requests.Item.Validators
{
public class AddItemRequestValidatorTests
{
private readonly AddItemRequestValidator _validator;

public AddItemRequestValidatorTests()
{
_validator = new AddItemRequestValidator();
}

[Fact]
public void should_have_error_when_ArtistId_is_null()
{
var addItemRequest = new AddItemRequest { Price = new Price() };
_validator.ShouldHaveValidationErrorFor(x => x.ArtistId, addItemRequest);
}

[Fact]
public void should_have_error_when_GenreId_is_null()
{
var addItemRequest = new AddItemRequest { Price = new Price() };
_validator.ShouldHaveValidationErrorFor(x => x.GenreId, addItemRequest);
}
}
}

The test class defined in the preceding code verifies that AddItemRequestValidator triggers a validation error if the GenreId or ArtistId fields are null. It uses the ShouldHaveValidationErrorFor extension method exposed by the TestHelper class to verify the behavior. The ShouldHaveValidationErrorFor method also exposes an IEnumerable of ValidationError, which can be used to check the details of each message of type ValidationError

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.166.7