我想用相同的测试类测试接口的所有实现。我已经知道TestCaseSourceAttribute,所以我将其设置为从静态testObjects数组加载对象实例。这段代码按照我想要的方式工作:
[TestFixture]
public class MySerializerTests
{
// IStreamSerializers loaded by the TestCaseSource attribute.
static object[] testObjects = new object[]
{
new BinarySerializer(),
new XmlSerializer(),
new JsonSerializer()
};
[Test, TestCaseSource("testObjects")]
public void Serialize_NullStreamArgument_ThrowsArgumentException(IStreamSerializer serializer)
{
Map map = new Map();
Assert.Throws<ArgumentNullException>(() => serializer.Serialize(null, map));
}
}
然而,我必须在每个方法上使用[TestCaseSource("testObjects")]
,这使得我拥有的方法数量相当繁琐。有没有一种方法可以将TextCaseSource属性替换为对整个测试类有效的属性?也许类似于参数化FestFixture的工作方式?
我想要类似这样的东西,但是我可以通过test类的构造函数来传递我测试的类的实例:
[TestFixture(0)]
[TestFixture(1)]
[TestFixture(2)]
public class MySerializerTests
{
// IStreamSerializers loaded by the TestCaseSource attribute.
static object[] testObjects = new object[]
{
new BinarySerializer(),
new XmlSerializer(),
new JsonSerializer()
};
int currentIndex;
public MySerializerTests(int index)
{
currentIndex = 0;
}
[Test]
public void Serialize_NullStreamArgument_ThrowsArgumentException()
{
Map map = new Map();
Assert.Throws<ArgumentNullException>(() => testObjects[currentIndex].Serialize(null, map));
}
}
发布于 2016-05-25 02:23:57
你想要TestFixtureSourceAttribute。
[TestFixtureSource("testObjects")]
public class MySerializerTests
{
// IStreamSerializers loaded by the TestCaseSource attribute.
static IStreamSerializer[] testObjects = new IStreamSerializer[]
{
new BinarySerializer(),
new XmlSerializer(),
new JsonSerializer()
};
IStreamSerializer _serializer;
public MySerializerTests(IStreamSerializer serializer)
{
_serializer = serializer;
}
[Test]
public void Serialize_NullStreamArgument_ThrowsArgumentException()
{
Map map = new Map();
Assert.Throws<ArgumentNullException>(
() => _serializer.Serialize(null, map));
}
}
我还没有编译这个,所以你可能需要修正打字错误,等等。
https://stackoverflow.com/questions/37380025
复制相似问题