dj5
dj5

Reputation: 81

Arrays.sort Issue?

I want to sort card objects that I made. I made an array to help sort the cards in order, however my Arrays.sort (cards) fails my junit test. Is there an issue with my testSort() method? My setUp() test passes so it isn't that.

import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.*;

public class CardTest {

   private Card twoOfClubs; 
   private Card fourOfDiamonds;
   private Card sixOfHearts;
   private Card tenOfSpades;

   @Before
    public void setUp() throws Exception {

       twoOfClubs = new Card(Rank.TWO, Suit.CLUBS);
       fourOfDiamonds = new Card(Rank.FOUR, Suit.DIAMONDS);
       sixOfHearts = new Card(Rank.SIX, Suit.HEARTS);
       tenOfSpades = new Card(Rank.TEN, Suit.SPADES);
   }

    @Test
    public void testSort() {

       Card[] cards = new Card[4];

       Arrays.sort(cards);

       assertEquals(twoOfClubs, cards[0]);
       assertEquals(fourOfDiamonds, cards[1]);
       assertEquals(sixOfHearts, cards[2]);
       assertEquals(tenOfSpades, cards[3])

   }
}

Upvotes: 1

Views: 176

Answers (2)

GhostCat
GhostCat

Reputation: 140465

And just for the record, you can write down your test in a much easier to read way:

Club[] expectedCards = { new Club ... };

Club[] sortedCards = ... running your "code to sort"

assertThat(sortedCards, is(expectedCards))

Upvotes: 0

Niles Tanner
Niles Tanner

Reputation: 4031

You never place the cards into the cards array. maybe change your @Before to something like this:

private Card[] cards;
@Before
    public void setUp() throws Exception {
       cards = new Card[4];
       twoOfClubs = new Card(Rank.TWO, Suit.CLUBS);
       fourOfDiamonds = new Card(Rank.FOUR, Suit.DIAMONDS);
       sixOfHearts = new Card(Rank.SIX, Suit.HEARTS);
       tenOfSpades = new Card(Rank.TEN, Suit.SPADES);
       cards = {tenOfSpades,fourOfDiamonds,twoOfClubs,sixOfHearts}
   }

Basically you need to add the cards to your test array some how.

Your test would then just look like:

 @Test
    public void testSort() {

       Arrays.sort(cards);

       assertEquals(twoOfClubs, cards[0]);
       assertEquals(fourOfDiamonds, cards[1]);
       assertEquals(sixOfHearts, cards[2]);
       assertEquals(tenOfSpades, cards[3])

   }

Upvotes: 4

Related Questions