Should I create a new constructor for test purposes only?

I have a class that contains a two-dimensional array of another object. It has one constructor, but inside this array is always initialized with zeros. Thus, it is Othersnot initialized to be fair:

public class FirstClass
{
    public OtherClass[,] Others { get; set; }

    ...

}

public class OtherClass
{
    public int Id { get; set; }
}

This array is Otherspopulated at runtime. Now I would like to write a test that will check some operations when filling Others. Therefore, I need to pass sample arrays to test methods. I did not want to create arrays OtherClassbecause I have many such arrays of samples, and I will have to write:

        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.. 

ugly!

So, in my project, TestsI created arrays only for ints ( 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}
        }
    };

much more readable ... but now I need to create a constructor for FirstClass, which takes int[,]as a parameter and creates OtherClass [,] with identifiers from the parameter.

Theoretically, I should be good, because the test will look like this:
[TestFixture]
class BoardTests
{
    [Test]
    [TestCaseSource("samples")]
    public void FirstTest(int[,] board)
    {
        FirstClass aClass = new FirstClass(board);
        //Test an operation on aClass 
    }
}

So my question is: Is it good practice to create an additional constructor ONLY for tests? I will not use this constructor in production code. Or do you have a better solution?

+4
source share
1 answer

FirstClass, int[,] OtherClass[,] Id .

, , , , , , . , , , 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}
    })
};
+2

Source: https://habr.com/ru/post/1611285/


All Articles