-
|
Hi, from the docs I saw that snippet : public class UserTestData : IEnumerable<User>
{
public IEnumerator<User> GetEnumerator()
{
yield return new User { Id = 1, Name = "Alice" };
yield return new User { Id = 2, Name = "Bob" };
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class UserTests
{
[Test]
[ClassDataSource<UserTestData>]
public async Task ValidateUser_ShouldPass(User user)
{
var isValid = await UserValidator.ValidateAsync(user);
await Assert.That(isValid).IsTrue();
}
}So I tried on my own project and it fail with TUnit0001 error Here is my simple code base on the one above from your docs : public record Users() { public int Id; public string Name; };
public class UsersDataSource : IEnumerable<Users>
{
public IEnumerator<Users> GetEnumerator()
{
yield return new Users { Id = 1, Name = "1" };
yield return new Users { Id = 2, Name = "2" };
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class MyTest
{
[Test]
public async Task Foo()
{
await Assert.That(true).IsTrue();
}
[Test]
[ClassDataSource<UsersDataSource>]
public async Task Bar(Users user)
{
await Assert.That(user.Name).Length().IsEqualTo(1);
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Hi! Thanks for the report — the docs were misleading.
For your scenario you have two clean options: 1. public static class UsersDataSource
{
public static IEnumerable<Users> All()
{
yield return new Users { Id = 1, Name = "1" };
yield return new Users { Id = 2, Name = "2" };
}
}
public class MyTest
{
[Test]
[MethodDataSource(typeof(UsersDataSource), nameof(UsersDataSource.All))]
public async Task Bar(Users user)
{
await Assert.That(user.Name).Length().IsEqualTo(1);
}
}2. Custom public sealed class UsersDataSourceAttribute : DataSourceGeneratorAttribute<Users>
{
protected override IEnumerable<Func<Users>> GenerateDataSources(DataGeneratorMetadata _)
{
yield return () => new Users { Id = 1, Name = "1" };
yield return () => new Users { Id = 2, Name = "2" };
}
}
public class MyTest
{
[Test]
[UsersDataSource]
public async Task Bar(Users user) { ... }
}
|
Beta Was this translation helpful? Give feedback.
Hi! Thanks for the report — the docs were misleading.
ClassDataSource<T>injects a single instance ofTinto the test; it does not enumerateTeven whenT : IEnumerable<U>. The example in the docs was wrong. I have just fixed it onmain(commit 17294ad).For your scenario you have two clean options:
1.
MethodDataSource(simplest) — works directly withIEnumerable<T>: