Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetUp, initialize Junit testing

I am trying to test my 3 classes that sorts string arrays in different ways!

I know that there is a method that initialize an array and then uses them in every single 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"};
    }
}

Eventhough I have tried both setUp and initialize method it doesn't seem to find x what have I done wrong?

like image 641
Marc Rasmussen Avatar asked Sep 18 '12 08:09

Marc Rasmussen


People also ask

Does setUp run before every test?

The @BeforeClass methods of superclasses will be run before those the current class. The difference being that setUpBeforeClass is run before any of the tests and is run once; setUp is run once before each test (and is usually used to reset the testing state to a known-good value between tests).


2 Answers

You need to make x a member variable of the class SortingTest

public class SortingTest {  

    private String[] x; 

    @Before
    public void init() {
      x = new String {"Ludo", "Chesstitans", "Palle", "Monkey"};
    }
}
like image 175
munyengm Avatar answered Nov 06 '22 05:11

munyengm


setUp should initialize some field member so other methods have access to it. If you initialize a local variable it will be lost when you exit setUp variable.

In this case the good thing would have two members:

  • originalArray
  • sortedArray

In each test method you could sort the originalArray and compare the result against your already sortedArray.

like image 39
helios Avatar answered Nov 06 '22 04:11

helios