Arrays.sort问题?

时间:2016-10-02 00:45:32

标签: arrays sorting junit

我想对我制作的卡片对象进行排序。我制作了一个数组来帮助按顺序排序卡片,但是我的Arrays.sort(卡片)未通过我的junit测试。我的testSort()方法有问题吗?我的setUp()测试通过,所以它不是。

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])

   }
}

2 个答案:

答案 0 :(得分:4)

您永远不会将卡片放入卡片阵列中。可能会将您的@Before更改为以下内容:

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

基本上你需要将卡片添加到你的测试阵列中。

您的测试将如下所示:

 @Test
    public void testSort() {

       Arrays.sort(cards);

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

   }

答案 1 :(得分:0)

只是为了记录,你可以用更容易阅读的方式写下你的测试:

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

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

assertThat(sortedCards, is(expectedCards))