Skip to content

Instantly share code, notes, and snippets.

@davepcallan
Created August 9, 2023 16:18

Revisions

  1. davepcallan created this gist Aug 9, 2023.
    78 changes: 78 additions & 0 deletions xUnitDataTests.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,78 @@
    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();
    }