我有一个包含另一个对象的二维数组的类.它有一个构造函数,但在该数组内部始终用零初始化.所以,其他人没有初始化为公平:
public class FirstClass
{
public OtherClass[,] Others { get; set; }
...
}
public class OtherClass
{
public int Id { get; set; }
}
其他人在运行时填充此数组.现在,我想编写一个测试,它将在填充其他人时测试一些操作.所以我需要将样本数组传递给Test方法.我不想创建OtherClass数组,因为我有很多这样的示例数组,我将不得不写:
OtherClass[][,] samples = new[]
{
new OtherClass[,]
{
{ new OtherClass() { Id = 2 };,new OtherClass() { Id = 2 };,new OtherClass() { Id = 2 };,new OtherClass() { Id = 2 };,new OtherClass() { Id = 2 };,new OtherClass() { Id = 2 };,new OtherClass() { Id = 2 };},
{ new OtherClass() { Id = 2 };,new OtherClass() { Id = 2 };,new OtherClass() { Id = 2 };,new OtherClass() { Id = 2 };,new OtherClass() { Id = 2 };,new OtherClass() { Id = 2 };,new OtherClass() { Id = 2 };},
etc..
丑陋!
所以在我的Tests项目中,我创建了一些int(Ids)数组:
int[][,] samples = new[]
{
new int[,]
{
{1,0,0,0,0,0,0},
{0,2,0,0,0,0,0},
{0,0,3,0,0,0,0},
{0,0,0,4,0,0,0}
},
new int[,]
{
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{1,2,3,4,5,6,7},
{0,0,0,0,0,0,0}
}
};
更可读……但是现在我需要为FirstClass创建一个构造函数,它将int [,]作为参数并使用参数中的Ids创建OtherClass [,].
理论上我应该是好的,因为测试看起来像:
[TestFixture]
class BoardTests
{
[Test]
[TestCaseSource("samples")]
public void FirstTest(int[,] board)
{
FirstClass aClass = new FirstClass(board);
//Test an operation on aClass
}
}
所以,我的问题是:
为测试创建额外的构造函数是一种好习惯吗?我不会在生产代码中使用此构造函数.或者你有更好的解决方案吗?
最佳答案
Now I need to create a constructor for
FirstClass
, that takesint[,]
as parameter and createOtherClass[,]
withId
s from parameter.
虽然这当然是一种选择,但如果您愿意,您当然不必这样做.保持构造函数不变的解决方案是在测试类中创建一个私有方法,将int [,]转换为OtherClass [,]:
private static ToOtherClass(int[,] ids) {
var OtherClass[,] res = ...
// Do the conversion here
return res;
}
现在,您可以使用此方法生成易于阅读的代码,该代码不使用特殊的构造函数:
OtherClass[][,] samples = new[]
{
ToOtherClass( new int[,]
{
{1,0,0,0,0,0,0},
{0,2,0,0,0,0,0},
{0,0,3,0,0,0,0},
{0,0,0,4,0,0,0}
}),
ToOtherClass( new int[,]
{
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{1,2,3,4,5,6,7},
{0,0,0,0,0,0,0}
})
};