Jam*_* Ko 7 .net c# xunit 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用SampleValuesas MemberData,所以我可以在这样的测试中使用它们
[Theory]
[MemberData(nameof(SampleValues))]
public void ItemShouldBeSameAsPassedInFromConstructor(T value)
{
var lease = CreateLease(value);
Assert.Equal(value, lease.Item);
}
Run Code Online (Sandbox Code Playgroud)
但是,对于所有使用的方法,我一直收到错误,说"没有找到[方法]的数据" SampleValues.在我进一步调查之后,我发现LeaseTests构造函数甚至没有被运行; 当我在通话中设置断点时AssignToSampleValues,它没有被击中.
为什么会发生这种情况,我该怎么做才能解决这个问题?谢谢.
构造函数未运行,因为MemberData在创建特定测试类的实例之前进行了评估。我不确定这是否能满足您的要求,但您可以执行以下操作:
定义ISampleDataProvider接口
public interface ISampleDataProvider<T>
{
IEnumerable<int> CreateSampleValues();
}
Run Code Online (Sandbox Code Playgroud)
添加类型具体实现:
public class IntSampleDataProvider : ISampleDataProvider<int>
{
public IEnumerable<int> CreateSampleValues()
{
yield return 3;
yield return 0;
yield return int.MaxValue;
yield return int.MinValue;
}
}
Run Code Online (Sandbox Code Playgroud)
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});
}
...
Run Code Online (Sandbox Code Playgroud)