Skip to content

Commit

Permalink
StringTooLong and tests (#332)
Browse files Browse the repository at this point in the history
  • Loading branch information
ardalis committed Dec 24, 2023
1 parent 4753832 commit 36051ca
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/GuardClauses/GuardAgainstStringLengthExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,36 @@ public static string StringTooShort(this IGuardClause guardClause,
}
return input;
}

/// <summary>
/// Throws an <see cref="ArgumentException" /> if string <paramref name="input"/> is too long.
/// </summary>
/// <param name="guardClause"></param>
/// <param name="input"></param>
/// <param name="maxLength"></param>
/// <param name="parameterName"></param>
/// <param name="message">Optional. Custom error message</param>
/// <returns><paramref name="input" /> if the value is not negative.</returns>
/// <exception cref="ArgumentException"></exception>
#if NETFRAMEWORK || NETSTANDARD2_0
public static string StringTooLong(this IGuardClause guardClause,
string input,
int maxLength,
string parameterName,
string? message = null)
#else
public static string StringTooLong(this IGuardClause guardClause,
string input,
int maxLength,
[CallerArgumentExpression("input")] string? parameterName = null,
string? message = null)
#endif
{
Guard.Against.NegativeOrZero(maxLength, nameof(maxLength));
if (input.Length > maxLength)
{
throw new ArgumentException(message ?? $"Input {parameterName} with length {input.Length} is too long. Maxmimum length is {maxLength}.", parameterName);
}
return input;
}
}
39 changes: 39 additions & 0 deletions test/GuardClauses.UnitTests/GuardAgainstStringTooLong.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System;
using Ardalis.GuardClauses;
using Xunit;

namespace GuardClauses.UnitTests;

public class GuardAgainstStringTooLong
{
[Fact]
public void DoesNothingGivenNonEmptyString()
{
Guard.Against.StringTooLong("a", 3, "string");
Guard.Against.StringTooLong("abc", 3, "string");
Guard.Against.StringTooLong("a", 3, "string");
Guard.Against.StringTooLong("a", 3, "string");
Guard.Against.StringTooLong("a", 3, "string");
}

[Fact]
public void ThrowsGivenNonPositiveMaxLength()
{
Assert.Throws<ArgumentException>(() => Guard.Against.StringTooLong("a", 0, "string"));
Assert.Throws<ArgumentException>(() => Guard.Against.StringTooLong("a", -1, "string"));
}

[Fact]
public void ThrowsGivenStringLongerThanMaxLength()
{
Assert.Throws<ArgumentException>(() => Guard.Against.StringTooLong("abc", 2, "string"));
}

[Fact]
public void ReturnsExpectedValueWhenGivenValidString()
{
var expected = "abc";
var actual = Guard.Against.StringTooLong("abc", 3, "string");
Assert.Equal(expected, actual);
}
}

0 comments on commit 36051ca

Please sign in to comment.