Xunit.net:未运行测试类构造函数



我正在尝试在我的xunit.net测试类之一中运行一些设置代码,但是尽管测试正在运行,但构造函数却没有。

这是我的一些代码:

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

我将SampleValues用作MemberData,因此我可以在这样的测试中使用它们

[Theory]
[MemberData(nameof(SampleValues))]
public void ItemShouldBeSameAsPassedInFromConstructor(T value)
{
    var lease = CreateLease(value);
    Assert.Equal(value, lease.Item);
}

但是,对于使用SampleValues的所有方法,我始终遇到一个错误,说"未找到[方法]的数据"。进一步调查后,我发现LeaseTests构造函数甚至没有运行。当我对AssignToSampleValues的呼叫设置断点时,它没有命中。

为什么会发生这种情况,我该怎么办?谢谢。

构造函数未运行,因为在创建特定测试类实例之前对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});
    }
...

相关内容

最新更新