patternjavaMinor
Unit testing for concatenating two int arrays
Viewed 0 times
arraysconcatenatingtwotestingforintunit
Problem
Using Java 1.8, I created the following implementation to
The unit test I created to test this looks like this:
Questions:
-
How could I change the actual implementation if I were to use varargs?
concat two int arrays:public static int[] concat(int[] array1, int[] array2) {
return IntStream.concat(Arrays.stream(array1), Arrays.stream(array2)).toArray();
}The unit test I created to test this looks like this:
int[] numbers1 = new int[] {1, 4, 3, 10, 2, 11, 15, 8};
int[] numbers2 = new int[] {5, 6, 7, 9, 12, 13, 14};
@Test
public void concat() {
int[] concatNumbers = ArrayUtils.concat(numbers1, numbers2);
for (int i = 0; i < numbers1.length; i++) {
assert(concatNumbers[i] == numbers1[i]);
}
for (int i = numbers2.length + 1; i < numbers2.length; i++) {
assert(concatNumbers[i] - 1 == numbers1[i]);
}
}Questions:
- Although my unit test works correctly, is there a better way to unit test this method (e.g. in terms of style, cleaner code, etc.)?
-
How could I change the actual implementation if I were to use varargs?
public static int[] concat(int[] ... args)Solution
Testing
-
Personally, for a test this simple, I'd tend to define the expected results for the test within it rather than calculating it on the fly. This makes it less likely that you'll get a failure because your test is wrong. It also allows you to use the junit array comparison.
-
You've only got one test, I'd tend to add at least 3 more for:
concatisn't a great name for a test, it doesn't tell me anything about what it is that the test does, it simply copies the name of the method being called. Something likeconcatShouldReturnConcatenationForTwoPopulatedArraysmight be a better description
-
Personally, for a test this simple, I'd tend to define the expected results for the test within it rather than calculating it on the fly. This makes it less likely that you'll get a failure because your test is wrong. It also allows you to use the junit array comparison.
Assert.assertArrayEquals( expectedResult, result );-
You've only got one test, I'd tend to add at least 3 more for:
concat([], numbers2)
concat(numbers1, [])
concat([], [])Code Snippets
Assert.assertArrayEquals( expectedResult, result );concat([], numbers2)
concat(numbers1, [])
concat([], [])Context
StackExchange Code Review Q#135359, answer score: 4
Revisions (0)
No revisions yet.