Skip to content

Instantly share code, notes, and snippets.

@jeroenheijmans
Last active November 28, 2016 14:12
Show Gist options
  • Save jeroenheijmans/19bc351a067596d313744fe88503511b to your computer and use it in GitHub Desktop.
Save jeroenheijmans/19bc351a067596d313744fe88503511b to your computer and use it in GitHub Desktop.
String Truncate method with test coverage
// CC-BY-SA 3.0, implementation by @LBushkin from http://stackoverflow.com/a/2776689/419956
public static class StringExtensions
{
public static string Truncate(this string value, int maxLength)
{
if (maxLength < 0) throw new ArgumentOutOfRangeException("maxLength");
if (string.IsNullOrEmpty(value)) return value;
return value.Length <= maxLength ? value : value.Substring(0, maxLength);
}
}
// NUnit TestFixture for coverage
[TestFixture]
public class StringExtensionsTests
{
[TestCase((string)null)]
[TestCase("")]
[TestCase(" ")]
[TestCase("\t")]
[TestCase("\r")]
[TestCase("\n")]
public void Truncate_WhenStringIsNothing_ReturnsOriginal(string value)
{
Assert.That(value.Truncate(1), Is.EqualTo(value));
}
[Test]
public void Truncate_WhenStringLengthIsEqualToMaxLength_ReturnsString()
{
Assert.That("four".Truncate(4), Is.EqualTo("four"));
}
[Test]
public void Truncate_WhenStringLengthIsSmallerThanMaxLength_ReturnsString()
{
Assert.That("one".Truncate(4), Is.EqualTo("one"));
}
[Test]
public void Truncate_WhenStringLengthIsLargerThanMaxLength_ReturnsString()
{
Assert.That("very long".Truncate(4), Is.EqualTo("very"));
}
[Test]
public void Truncate_WhenMaxLengthIsZero_ReturnsEmptyString()
{
Assert.That("text".Truncate(0), Is.EqualTo(""));
}
[Test]
public void Truncate_WhenMaxLengthIsNegative_ThrowsArgumentOutOfRangeException()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => "text".Truncate(-1));
Assert.That(ex.ParamName, Is.EqualTo("maxLength"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment