c# – 我是否应该仅为测试目的创建新的构造函数?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 我是否应该仅为测试目的创建新的构造函数?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2223字,纯文字阅读大概需要4分钟。
内容图文
我有一个包含另一个对象的二维数组的类.它有一个构造函数,但在该数组内部始终用零初始化.所以,其他人没有初始化为公平:
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}
})
};
内容总结
以上是互联网集市为您收集整理的c# – 我是否应该仅为测试目的创建新的构造函数?全部内容,希望文章能够帮你解决c# – 我是否应该仅为测试目的创建新的构造函数?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。