c# - 我应该只为测试目的创建新的构造函数吗?

标签 c# unit-testing testing nunit integration-testing

我有一个包含另一个对象的二维数组的类。它有一个构造函数,但在该数组内部总是用零初始化。因此,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 是好习惯吗?我不会在生产代码中使用这个构造函数。或者您有更好的解决方案吗?

最佳答案

Now I need to create a constructor for FirstClass, that takes int[,] as parameter and create OtherClass[,] with Ids from parameter.

虽然这当然是一个选项,但如果您愿意,您当然必须这样做。保持构造函数不变的解决方案是在测试类中创建一个私有(private)方法,将 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# - 我应该只为测试目的创建新的构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33081867/

相关文章:

javascript - Jest 模拟一个对象

node.js - 使用 Sequelize 构建、播种和销毁 PostgreSQL 以进行测试

c# - 在C# asp.net中动态添加用户控件

c# - 使用 ASP.NET Identity 重置密码时 token 无效

c# - 使用 C# 将 PDF 转换为 XPS 的免费方法

c# - 谷歌地图处理服务器端

php - 为什么 Symfony 3 单元测试从实际的包中移出?

java - Play 2.4 中的 Guice、DI 和单元测试

testing - Wicket 口和AtUnit

sql - ActiveRecord 在 Rspec 测试中导致 SQLException