ObjectHydrator icon indicating copy to clipboard operation
ObjectHydrator copied to clipboard

Fix TextGenerator to handle small StringLength attributes without exceptions

Open Copilot opened this issue 7 months ago • 0 comments

The TextGenerator.Generate() method was throwing ArgumentOutOfRangeException when used with small StringLength attribute values (1 or 2 characters). This was causing random failures when generating objects with properties decorated with [StringLength(1)] or [StringLength(2)].

Root Cause

The issue was in the random number generation logic:

return sampleText.Substring(0, random.Next(1, Length - 1)).Trim();

When Length was small, this created invalid ranges:

  • Length = 1: random.Next(1, 0)minValue > maxValue → Exception
  • Length = 2: random.Next(1, 1)minValue == maxValue → Exception

Solution

Replaced the problematic logic with proper bounds checking and special handling for edge cases:

public string Generate()
{
    // Ensure we have a valid length to work with
    int maxLength = Math.Min(Length, sampleText.Length);
    
    if (maxLength <= 0)
        return string.Empty;
    
    if (maxLength == 1)
        return sampleText.Substring(0, 1).Trim();
    
    // For lengths 2 and above, generate a random length between 1 and maxLength (inclusive)
    int randomLength = random.Next(1, maxLength + 1);
    return sampleText.Substring(0, randomLength).Trim();
}

Testing

  • All existing 111 tests continue to pass
  • Added 4 new comprehensive tests covering edge cases:
    • [StringLength(4000)] - large values
    • [StringLength(1)] - minimum edge case
    • [StringLength(2)] - second edge case
    • Multiple iterations to test randomness
  • Manual testing confirms proper behavior across all scenarios

The fix is minimal and surgical, preserving all existing functionality while safely handling the edge cases that were causing exceptions.

Fixes #11.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copilot avatar Jul 15 '25 15:07 Copilot