XUnit.net: class class constructors do not start?

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();
}

// Specialize the test class for different types
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.

+6
1

, MemberData . , , :

ISampleDataProvider

public interface ISampleDataProvider<T>
{
    IEnumerable<int> CreateSampleValues();
}

:

public class IntSampleDataProvider : ISampleDataProvider<int>
{
    public IEnumerable<int> CreateSampleValues()
    {
        yield return 3;
        yield return 0;
        yield return int.MaxValue;
        yield return int.MinValue;
    }
}

SampleValues

public abstract class LeaseTests<T>
{
    public static IEnumerable<object[]> SampleValues()
    {
        var targetType = typeof (ISampleDataProvider<>).MakeGenericType(typeof (T));

        var sampleDataProviderType = Assembly.GetAssembly(typeof (ISampleDataProvider<>))
                                                .GetTypes()
                                                .FirstOrDefault(t => t.IsClass && targetType.IsAssignableFrom(t));

        if (sampleDataProviderType == null)
        {
            throw new NotSupportedException();
        }

        var sampleDataProvider = (ISampleDataProvider<T>)Activator.CreateInstance(sampleDataProviderType);
        return sampleDataProvider.CreateSampleValues().Select(value => new object[] {value});
    }
...
+3

All Articles