-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Closed
Milestone
Description
FluentValidation version
11.1.2
ASP.NET version
5
Summary
During unit testing, I'm using Only() for a certain property and the test is still passing even when there are multiple validation failures on different properties.
Steps to Reproduce
I used the following example code to reproduce this error:
PersonDto.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Client.WebService.Tests.Playground
{
public class PersonDto
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
}
}
PersonValidator.cs
using Client.WebService.Common.Services.Interfaces;
using Client.WebService.Features.Athletes.DataAccessors.Interfaces;
using Client.WebService.Features.Athletes.Dtos.Request;
using Client.WebService.Features.Athletes.Persistence.Entities;
using FluentValidation;
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
namespace Client.WebService.Tests.Playground
{
public class PersonValidator : AbstractValidator<PersonDto>
{
public PersonValidator()
{
RuleFor(command => command.FirstName)
.NotEmpty()
.WithMessage("First name is required");
RuleFor(command => command.MiddleName)
.NotEmpty()
.WithMessage("Middle name is required");
RuleFor(command => command.LastName)
.NotEmpty()
.WithMessage("Last name is required");
}
}
}
PersonValidatorTests.cs
using FluentValidation.TestHelper;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Client.WebService.Tests.Playground
{
[TestClass]
public class PersonValidatorTests
{
private readonly PersonValidator _personValidator;
public PersonValidatorTests()
{
_personValidator = new PersonValidator();
}
[TestMethod]
public void Test1()
{
// Arrange
var personDto = new PersonDto()
{
FirstName = "",
MiddleName = "",
LastName = "Sherman",
};
// Act
var result = _personValidator.TestValidate(personDto);
// Assert
result
.ShouldHaveValidationErrorFor(personDto => personDto.FirstName)
.WithErrorMessage("First name is required")
.Only();
}
}
}
If you debug this test, you will notice there's a validation error for both first name and middle name, but the test should fail because it's only expecting 1 validation error with that specific error message for FirstName
Metadata
Metadata
Assignees
Labels
No labels