I'm making an Unit test for a Request with dates. These dates are with the same timestamps and the test is failing. With different timestamps the test is running well, but with equal timestamps the test is returning an error result.
Code for test:
[Fact]
public void ShouldHaveValidationSuccessWhenStartDateIsLessOrEqualToFinishDate()
{
//Arrange
var request = new RegisterRequest { FinishDate = DateTimeOffset.UtcNow, StartDate = DateTimeOffset.UtcNow };
var sut = new RegisterRequestValidator();
//Act
var result = sut.TestValidate(request);
//Assert
result.ShouldNotHaveValidationErrorFor(x => x.StartDate);
}
Code for validator:
public RegisterRequestValidator()
{
RuleFor(req => req.StartDate).LessThanOrEqualTo(req => req.FinishDate).When(HasStartDate);
}
protected bool HasStartDate(RegisterRequest req) => req.StartDate != null;
Code for RegisterRequest:
public sealed class RegisterRequest : IRequest<OperationResult<IQueryable<EntityViewModel>>>
{
public DateTimeOffset? StartDate { get; set; }
public DateTimeOffset? FinishDate { get; set; }
}
The error I'm getting is
Message:
FluentValidation.TestHelper.ValidationTestException : Expected no validation errors for property StartDate
----
Validation Errors:
[0]: 'Start Date' must be less than or equal to '07/11/2019 12:50:58 +00:00'.
Why this is happening?
You are getting a different result from DateTimeOffset.UtcNow
because it is being called twice in the RegisterRequest
constructor. Try:
var utcNow = DateTimeOffset.UtcNow;
var request = new RegisterRequest { FinishDate = utcNow, StartDate = utcNow };