Skip to content

Commit

Permalink
#3053: Class data derived from TheoryData<SomeType[]> is broken
Browse files Browse the repository at this point in the history
  • Loading branch information
bradwilson committed Nov 7, 2024
1 parent 5f7494f commit bfd42e0
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 12 deletions.
26 changes: 14 additions & 12 deletions src/xunit.core/ClassDataAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,21 @@ public ClassDataAttribute(Type @class)
/// <inheritdoc/>
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
IEnumerable<object[]> data = Activator.CreateInstance(Class) as IEnumerable<object[]>;
if (data == null)
throw new ArgumentException(
string.Format(
CultureInfo.CurrentCulture,
"{0} must implement IEnumerable<object[]> to be used as ClassData for the test method named '{1}' on {2}",
Class.FullName,
testMethod.Name,
testMethod.DeclaringType.FullName
)
);
var dataObj = Activator.CreateInstance(Class);
if (dataObj is ITheoryData theoryData)
return theoryData.GetData();
if (dataObj is IEnumerable<object[]> enumerable)
return enumerable;

return data;
throw new ArgumentException(
string.Format(
CultureInfo.CurrentCulture,
"{0} must implement IEnumerable<object[]> to be used as ClassData for the test method named '{1}' on {2}",
Class.FullName,
testMethod.Name,
testMethod.DeclaringType.FullName
)
);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,41 @@ public IEnumerator<object[]> GetEnumerator()
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

[Fact]
public void ClassDataFromArray()
{
var testMessages = Run<ITestResultMessage>(typeof(ClassWithArrayData));

Assert.Collection(
testMessages.OfType<ITestPassed>().Select(p => p.Test.DisplayName).OrderBy(x => x),
name => Assert.Equal("Xunit2TheoryAcceptanceTests+ClassDataTests+ClassWithArrayData.ExampleParameterizedTestMethod(values: [\"0\", \"2\", \"4\"])", name),
name => Assert.Equal("Xunit2TheoryAcceptanceTests+ClassDataTests+ClassWithArrayData.ExampleParameterizedTestMethod(values: [\"0\", \"2\"])", name),
name => Assert.Equal("Xunit2TheoryAcceptanceTests+ClassDataTests+ClassWithArrayData.ExampleParameterizedTestMethod(values: [\"0\"])", name)
);
Assert.Empty(testMessages.OfType<ITestFailed>());
Assert.Empty(testMessages.OfType<ITestSkipped>());
}

class ClassWithArrayData
{
[Theory]
[ClassData(typeof(ClassDataFromArrayDataSource))]
public void ExampleParameterizedTestMethod(string[] values)
{
Assert.All(values, s => Assert.True(s.Length < 10));
}
}

class ClassDataFromArrayDataSource : TheoryData<string[]>
{
public ClassDataFromArrayDataSource()
{
Add(["0"]);
Add(["0", "2"]);
Add(["0", "2", "4"]);
}
}

[Fact]
public void NoDefaultConstructor_Fails()
{
Expand Down

0 comments on commit bfd42e0

Please sign in to comment.