Home > Net >  FluentAssertions alternative of TrueForAll
FluentAssertions alternative of TrueForAll

Time:10-15

I'm trying to find an alternative of .TrueForAll using FluentAssertions. Note that in the Shoudly example Products is List<Product> whereas in the new code it is IEnumerable<Product>.

It says A constant value is expected for minPrice and maxPrice:

actual.Products.All(x => x.Price is >= minPrice and <= maxPrice).Should().BeTrue(); // A constant value is expected

// or
actual.Products.Should().OnlyContain(x => x.Price is >= minPrice and <= maxPrice); // A constant value is expected

Shoudly (old code)

[Theory]
[InlineData(10)]
[InlineData(12)]
[InlineData(5)]

public async Task Handle_ReturnsFilteredProductByMaxPrice(double maxPrice)
{
    var parameters = new ProductParams() { MaxPrice = maxPrice };

    var result = await _handler.Handle(new GetProductsQuery(parameters), CancellationToken.None);

    result.Value.Products.TrueForAll(x => x.Price <= maxPrice);
}

FluentAssertions (new code)

[Theory]
[InlineData(10, 14)]
[InlineData(22, 24)]
public async Task Handle_ShouldReturnFilteredSubsetOfProducts_WhenGivenMinPriceAndMaxPrice(double minPrice, double maxPrice)
{
    // Arrange
    var query = new GetProductsQuery(MinPrice: minPrice, MaxPrice: maxPrice);

    // Act
    var actual = await _queryHandler.Handle(query, default);

    // Assert
    actual.Products.All(x => x.Price is >= minPrice and <= maxPrice).Should().BeTrue();
}
public record Product(
    [property: JsonPropertyName("title")] string Title,
    [property: JsonPropertyName("price")] double Price,
    [property: JsonPropertyName("sizes")] List<string> Sizes,
    [property: JsonPropertyName("description")] string Description);

CodePudding user response:

https://fluentassertions.com/collections/

actual.Products.Should().OnlyContain(x => x.Price >= minPrice && x.Price <= maxPrice)

The error you're getting comes from incorrect use of pattern matching - the values after is need to be constant, not a variable.

  • Related