Skip to content

Commit

Permalink
Fixes #253
Browse files Browse the repository at this point in the history
  • Loading branch information
ardalis committed Aug 1, 2023
1 parent 3f44649 commit f70b07b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/GuardClauses/GuardAgainstExpressionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,26 @@ public static async Task<T> AgainstExpressionAsync<T>(this IGuardClause guardCla

return input;
}

/// <summary>
/// Throws an <see cref="ArgumentException" /> if <paramref name="func"/> evaluates to false for given <paramref name="input"/>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="func"></param>
/// <param name="guardClause"></param>
/// <param name="input"></param>
/// <param name="message"></param>
/// <param name="paramName">The name of the parameter that is invalid</param>
/// <returns><paramref name="input"/> if the <paramref name="func"/> evaluates to true </returns>
/// <exception cref="ArgumentException"></exception>
public static T AgainstExpression<T>(this IGuardClause guardClause, Func<T, bool> func,
T input, string message, string paramName) where T : struct
{
if (!func(input))
{
throw new ArgumentException(message, paramName);
}

return input;
}
}
10 changes: 10 additions & 0 deletions test/GuardClauses.UnitTests/GuardAgainstExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,14 @@ public void ErrorMessageMatchesExpected(string customMessage, string expectedMes
Assert.NotNull(exception.Message);
Assert.Equal(expectedMessage, exception.Message);
}

[Fact]
public void ErrorIncludesParamNameIfProvided()
{
string paramName = "testParamName";
var exception = Assert.Throws<ArgumentException>(() => Guard.Against.AgainstExpression(x => x == 1, 2, "custom message", paramName));
Assert.NotNull(exception);
Assert.NotNull(exception.Message);
Assert.Equal(paramName, exception.ParamName);
}
}

0 comments on commit f70b07b

Please sign in to comment.