Is it OK to repeat code for unit tests?
Posted
by
Pete
on Programmers
See other posts from Programmers
or by Pete
Published on 2012-03-18T19:44:34Z
Indexed on
2012/03/19
2:15 UTC
Read the original article
Hit count: 243
testing
I wrote some sorting algorithms for a class assignment and I also wrote a few tests to make sure the algorithms were implemented correctly. My tests are only like 10 lines long and there are 3 of them but only 1 line changes between the 3 so there is a lot of repeated code. Is it better to refactor this code into another method that is then called from each test? Wouldn't I then need to write another test to test the refactoring? Some of the variables can even be moved up to the class level. Should testing classes and methods follow the same rules as regular classes/methods?
Here's an example:
[TestMethod]
public void MergeSortAssertArrayIsSorted()
{
int[] a = new int[1000];
Random rand = new Random(DateTime.Now.Millisecond);
for(int i = 0; i < a.Length; i++)
{
a[i] = rand.Next(Int16.MaxValue);
}
int[] b = new int[1000];
a.CopyTo(b, 0);
List<int> temp = b.ToList();
temp.Sort();
b = temp.ToArray();
MergeSort merge = new MergeSort();
merge.mergeSort(a, 0, a.Length - 1);
CollectionAssert.AreEqual(a, b);
}
[TestMethod]
public void InsertionSortAssertArrayIsSorted()
{
int[] a = new int[1000];
Random rand = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < a.Length; i++)
{
a[i] = rand.Next(Int16.MaxValue);
}
int[] b = new int[1000];
a.CopyTo(b, 0);
List<int> temp = b.ToList();
temp.Sort();
b = temp.ToArray();
InsertionSort merge = new InsertionSort();
merge.insertionSort(a);
CollectionAssert.AreEqual(a, b);
}
© Programmers or respective owner