|
| 1 | +package com.baeldung.array; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertArrayEquals; |
| 4 | +import static org.junit.Assert.assertEquals; |
| 5 | + |
| 6 | +import java.io.ByteArrayInputStream; |
| 7 | +import java.io.ByteArrayOutputStream; |
| 8 | +import java.io.InputStream; |
| 9 | +import java.io.PrintStream; |
| 10 | + |
| 11 | +import org.junit.Test; |
| 12 | + |
| 13 | +public class JaggedArrayTest { |
| 14 | + |
| 15 | + private JaggedArray obj = new JaggedArray(); |
| 16 | + |
| 17 | + @Test |
| 18 | + public void whenInitializedUsingShortHandForm_thenCorrect() { |
| 19 | + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization()); |
| 20 | + } |
| 21 | + |
| 22 | + @Test |
| 23 | + public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() { |
| 24 | + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization()); |
| 25 | + } |
| 26 | + |
| 27 | + @Test |
| 28 | + public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() { |
| 29 | + InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes()); |
| 30 | + System.setIn(is); |
| 31 | + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs()); |
| 32 | + System.setIn(System.in); |
| 33 | + } |
| 34 | + |
| 35 | + @Test |
| 36 | + public void givenJaggedArrayAndAnIndex_thenReturnArrayAtGivenIndex() { |
| 37 | + int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; |
| 38 | + assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(jaggedArr, 0)); |
| 39 | + assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(jaggedArr, 1)); |
| 40 | + assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(jaggedArr, 2)); |
| 41 | + } |
| 42 | + |
| 43 | + @Test |
| 44 | + public void givenJaggedArray_whenUsingArraysAPI_thenVerifyPrintedElements() { |
| 45 | + int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; |
| 46 | + ByteArrayOutputStream outContent = new ByteArrayOutputStream(); |
| 47 | + System.setOut(new PrintStream(outContent)); |
| 48 | + obj.printElements(jaggedArr); |
| 49 | + assertEquals("[1, 2]\n[3, 4, 5]\n[6, 7, 8, 9]\n", outContent.toString()); |
| 50 | + System.setOut(System.out); |
| 51 | + } |
| 52 | + |
| 53 | +} |
0 commit comments