Skip to content

Instantly share code, notes, and snippets.

@davepcallan
Created January 22, 2025 16:36
Show Gist options
  • Save davepcallan/0334e5ed05f32f244b64ef7440111677 to your computer and use it in GitHub Desktop.
Save davepcallan/0334e5ed05f32f244b64ef7440111677 to your computer and use it in GitHub Desktop.
Unit Test case example showing that it's the contract of a method and not the implementation that should dictate the number of tests.
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
public class StringReverser
{
// Method 1: Concise Implementation (2 lines)
// Contract: Reverse the input string and return the result.
public static string ReverseStringConcise(string input)
{
if (string.IsNullOrEmpty(input)) return input;
return string.Concat(input.Reverse());
}
// Method 2: Verbose Implementation (15 lines)
// Contract: Reverse the input string and return the result.
public static string ReverseStringVerbose(string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}
char[] charArray = new char[input.Length];
for (int i = 0; i < input.Length; i++)
{
charArray[i] = input[input.Length - 1 - i];
}
string reversed = "";
foreach (var c in charArray)
{
reversed += c;
}
return reversed;
}
}
public class StringReverserTests
{
// Shared test cases using MemberData
public static IEnumerable<object[]> TestCases =>
new List<object[]>
{
new object[] { "Hello", "olleH" }, // Normal case
new object[] { "", "" }, // Empty string
new object[] { "A", "A" }, // Single character
new object[] { null, null }, // Null input
new object[] { "12345", "54321" }, // Numeric string
new object[] { "!@#$", "$#@!" }, // Special characters
new object[] { "AbCdE", "EdCbA" }, // Mixed case
new object[] { "a b c", "c b a" }, // String with spaces
new object[] { "πŸ˜ŠπŸŽ‰", "πŸŽ‰πŸ˜Š" }, // Unicode characters
new object[] { "aaaa", "aaaa" }, // Repeated characters
new object[] { "a\nb\nc", "c\nb\na" }, // String with newlines
new object[] { "LongString12345", "54321gnirtSgnoL" } // Longer string
};
[Theory]
[MemberData(nameof(TestCases))]
public void ReverseStringConcise_ShouldReturnCorrectlyReversedString(string input, string expected)
{
// Act
var result = StringReverser.ReverseStringConcise(input);
// Assert
Assert.Equal(expected, result);
}
[Theory]
[MemberData(nameof(TestCases))]
public void ReverseStringVerbose_ShouldReturnCorrectlyReversedString(string input, string expected)
{
// Act
var result = StringReverser.ReverseStringVerbose(input);
// Assert
Assert.Equal(expected, result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment