【发布时间】:2016-01-09 23:25:30
【问题描述】:
我有一个包含另一个对象的二维数组的类。它有一个构造函数,但在该数组内部总是用零初始化。所以,Others 没有被初始化为公平:
public class FirstClass
{
public OtherClass[,] Others { get; set; }
...
}
public class OtherClass
{
public int Id { get; set; }
}
此数组Others 在运行时填充。现在,我想编写一个测试,在填充Others 时测试一些操作。所以我需要将样本数组传递给测试方法。我不想创建 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 项目中,我只创建了整数数组 (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[,] 作为参数并使用来自参数的ID 创建OtherClass[,]。
理论上我应该很好,因为测试看起来像:
[TestFixture]
class BoardTests
{
[Test]
[TestCaseSource("samples")]
public void FirstTest(int[,] board)
{
FirstClass aClass = new FirstClass(board);
//Test an operation on aClass
}
}
所以,我的问题是: 为测试创建额外的构造函数 ONLY 是一种好习惯吗?我不会在生产代码中使用这个构造函数。或者你有更好的解决方案?
【问题讨论】:
-
只是一个问题,无论如何'Others' 是作为公共属性公开的,所以为什么不使用您在测试中想要的任何值对其进行初始化呢?
-
您可以创建一个单独的类,在 int[,] 和 Other[] 之间进行映射(与您将在新构造函数中编写的代码相同)。这样你就分离了逻辑。
标签: c# unit-testing testing nunit integration-testing