Skip to content

Instantly share code, notes, and snippets.

@davepcallan
Created August 9, 2023 16:18
Show Gist options
  • Save davepcallan/7c70f4513715ed04fd451899fa42606a to your computer and use it in GitHub Desktop.
Save davepcallan/7c70f4513715ed04fd451899fa42606a to your computer and use it in GitHub Desktop.
Parameterized Tests with xUnit Example
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Xunit;
public class StringFormatter
{
public string Reverse(string input)
{
switch (input)
{
case "abc":
return "cba";
case "hello":
return "olleh";
case "world":
return "dlrow";
default:
throw new ArgumentException($"No reverse mapping defined for '{input}'.");
}
}
}
public class StringFormatterTests
{
// Using InlineData
[Theory]
[InlineData("abc", "cba")]
[InlineData("hello", "olleh")]
[InlineData("world", "dlrow")]
public void Reverse_WithInlineData_ReturnsCorrectResult(string input, string expected)
{
var stringFormatter = new StringFormatter();
var result = stringFormatter.Reverse(input);
Assert.Equal(expected, result);
}
// Using TheoryData
public static TheoryData<string, string> ReverseTestData =>
new TheoryData<string, string>
{
{ "abc", "cba" },
{ "hello", "olleh" },
{ "world", "dlrow" }
};
[Theory]
[MemberData(nameof(ReverseTestData))]
public void Reverse_WithTheoryData_ReturnsCorrectResult(string input, string expected)
{
var stringFormatter = new StringFormatter();
var result = stringFormatter.Reverse(input);
Assert.Equal(expected, result);
}
// Using ClassData
[Theory]
[ClassData(typeof(ReverseTestCases))]
public void Reverse_WithClassData_ReturnsCorrectResult(string input, string expected)
{
var stringFormatter = new StringFormatter();
var result = stringFormatter.Reverse(input);
Assert.Equal(expected, result);
}
}
public class ReverseTestCases : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[] { "abc", "cba" };
yield return new object[] { "hello", "olleh" };
yield return new object[] { "world", "dlrow" };
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment