Marc Rasmussen
Marc Rasmussen

Reputation: 20555

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?

Upvotes: 9

Views: 35077

Answers (3)

munyengm
munyengm

Reputation: 15479

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"};
    }
}

Upvotes: 14

Igor
Igor

Reputation: 1

You need to make x a member of a class, so that it's visible in all methods.

Upvotes: 0

helios
helios

Reputation: 13841

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.

Upvotes: 2

Related Questions