I am trying to run some setup code in one of my xUnit.net test classes, but although the tests are running, it does not look like a constructor.
Here are some of my codes:
public abstract class LeaseTests<T>
{
private static readonly object s_lock = new object();
private static IEnumerable<T> s_sampleValues = Array.Empty<T>();
private static void AssignToSampleValues(Func<IEnumerable<T>, IEnumerable<T>> func)
{
lock (s_lock)
{
s_sampleValues = func(s_sampleValues);
}
}
public LeaseTests()
{
AssignToSampleValues(s => s.Concat(CreateSampleValues()));
}
public static IEnumerable<object[]> SampleValues()
{
foreach (T value in s_sampleValues)
{
yield return new object[] { value };
}
}
protected abstract IEnumerable<T> CreateSampleValues();
}
public class IntLeaseTests : LeaseTests<int>
{
protected override IEnumerable<int> CreateSampleValues()
{
yield return 3;
yield return 0;
yield return int.MaxValue;
yield return int.MinValue;
}
}
I use SampleValueshow MemberData, so I can use them in tests like this
[Theory]
[MemberData(nameof(SampleValues))]
public void ItemShouldBeSameAsPassedInFromConstructor(T value)
{
var lease = CreateLease(value);
Assert.Equal(value, lease.Item);
}
However, I constantly get a "no data for [method]" error message for all methods that use SampleValues. After exploring further, I found that the constructor LeaseTestsdid not even start; when I set a breakpoint on call AssignToSampleValues, it didn’t hit.
Why is this happening, and what can I do to fix it? Thank.