Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}