DynamicsValue / fake-xrm-easy

FakeXrmEasy: The Test Automation Framework for the Power Platform / Dataverse
https://dynamicsvalue.github.io/fake-xrm-easy-docs/why/
Other
25 stars 12 forks source link

XrmAttributeExpression with count aggregate does not yield the expected result #155

Open leonmastenbroek opened 2 months ago

leonmastenbroek commented 2 months ago

Given this method:

public int GetTotalCount(QueryExpression expression, string groupByField = "")
{
    var strippedExpression = new QueryExpression(expression.EntityName)
    {
        ColumnSet = new ColumnSet(false)
        {
            AttributeExpressions =
            {
                new XrmAttributeExpression(
                    attributeName: string.IsNullOrWhiteSpace(groupByField) ? $"{expression.EntityName}id" : groupByField,
                    alias: $"{expression.EntityName}count",
                    aggregateType: XrmAggregateType.Count)
            }
        },
        Criteria = expression.Criteria
    };

    if (expression.LinkEntities.Any())
    {
        strippedExpression.LinkEntities.AddRange(expression.LinkEntities.Select(l =>
        {
            l.Columns = new ColumnSet(false);
            return l;
        }));
    }

    var response = organizationService.RetrieveMultiple(strippedExpression);
    var aliasedValue = response?.Entities?.First().GetAttributeValue<AliasedValue>(($"{expression.EntityName}count"));

    return (int) (aliasedValue?.Value ?? 0);
}

Problem In production environments, the method correctly returns the aggregate count of the QueryExpression. However, in test scenarios, the method retrieves the entities instead of the aggregate count. This behavior is unexpected and leads to incorrect results during testing.

Test method

public void CountLargeList_CountReturnsMoreThan5000()
{
    // Arrange
    var numberOfTickets = 5050;
    var incidents = Enumerable.Range(1, numberOfTickets)
        .Select(i => new Incident {
            Id = Guid.NewGuid(),
            Title = $"Test {i}",
        })
        .ToList<Incident>();

    Context.Initialize(incidents);

    // Act
    var countResult = _dynamicsService.GetTotalCount(new QueryExpression(Incident.EntityLogicalName));

    // Assert
    countResult.Should().Be(numberOfTickets);
}
jordimontana82 commented 2 months ago

Thanks Leon for raising this @leonmastenbroek

We'll investigate and get back to you.

If you're using FXE under a commercial license please drop us an email to support so we can prioritise it.