SetUp, initialize Junit testing

I am trying to test my 3 classes that sort string arrays differently!

I know that there is a method that initializes the array and then uses them in each of my tests.

So far this is my code:

public class SortingTest { public insertionSort is = new insertionSort(); public bubbleSort bs = new bubbleSort(); @Test public void testBubbleSort() { String [] sortedArray ={"Chesstitans", "Ludo", "Monkey", "Palle"}; bs.sort(sortedArray); assertArrayEquals(sortedArray, x); } @Test public void testInsertionSort() { } @Test public void testMergeSort() { } @Test public void testSelectionSort() { } @Before protected void setUp() throws Exception{ String[]x ={"Ludo", "Chesstitans", "Palle", "Monkey"}; } } 

Despite the fact that I tried both the setUp and initialize methods, it doesn't seem to find x, what did I do wrong?

+7
source share
3 answers

You need to make x member variable of the SortingTest class

 public class SortingTest {  private String[] x; @Before public void init() { x = new String {"Ludo", "Chesstitans", "Palle", "Monkey"}; } } 
+11
source

setUp must initialize some member of the field so that other methods have access to it. If you initialize a local variable, it will be lost when you exit the setUp variable.

In this case, a good thing would have two members:

  • originalArray
  • sortedArray

In each test method, you can sort the source array and compare the result with an already sorted array.

+2
source

You need to make x member of the class so that it appears in all methods.

0
source

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


All Articles