如何创建可以验证一组扑克牌的测试类?

时间:2017-12-06 19:51:52

标签: java class

我正在尝试通过使用类来编写Java游戏。我必须创建一个测试类来验证所调用方法的结果,并打印出一个横幅,其中每个测试都指出测试失败或通过,以及最终横幅以查看是否所有测试都通过或失败。

PlayingCard Class (此类需要成为测试人员)

import java.util.ArrayList;
import java.util.Random;

public class PlayingCards
{
    private ArrayList<Card> m_Cards;
    private Random gen;

    /**
     No-arg constructor initializes m_Cards.

     Initialize the ArrayList head and the random number generator.
     */
    public PlayingCards()
    {
        m_Cards = new ArrayList<Card> ();
        gen = new Random ();
    }

    /**
     Get the number of cards.    

     @return number of cards
     */
    public int size()
    {
        return m_Cards.size();
    }

    /**
     Add a card.
     */
    public void addCard(Card newCard)
    {
        m_Cards.add(newCard);
    }

    /**
     Remove a card.

     @return null if there are no cards to remove or the instance field is null.
             Otherwise, returns a reference to a Card.
     */
    public Card removeCard()
    {
        if (m_Cards.size() == 0)
            return null;

        else
            return m_Cards.remove(0);
    }

    /**
     Shuffle the cards.

     This method shuffles the cards.
     */
    public void shuffle()
    {
        if ((m_Cards == null) || (m_Cards.size() < 2))
            return;

        for (int ii = 0; ii < m_Cards.size(); ++ii)
        {
            Card a = m_Cards.get(ii);
            int swapIndex = gen.nextInt(m_Cards.size());

            Card b = m_Cards.get(swapIndex);

            // swap the positions of a and b
            m_Cards.set(ii, b);
            m_Cards.set(swapIndex, a);
        }
    }

    /**
     Implement the toString method to show the contents of a
     PlayingCards object.

     This method relies on Card.toString() method.
     */
    @Override
    public String toString()
    {
        String outPut = "";

        for (int i = 0; i < m_Cards.size(); i++)
        {
            outPut += m_Cards.get(i).toString();
            outPut += "\n";
        }

        return outPut;
    }
}

1 个答案:

答案 0 :(得分:0)

如果您不想使用JUnit

编写一个创建PlayingCards实例的新类,然后调用该类的方法。使用assert验证您预计会发生什么。例如:

public class PlayingCardsTest {
  private PlayingCards playingCards;

  PlayingCardsTest() {
    playingCards = new PlayingCards();
  }

  public void testAddCard() {
    playingCards.addCard(new Card());

    assert playingCards.size() == 1;
  }
}

然后,您可以创建一个main来创建新的PlayingCardsTest并调用每个测试方法。

您还可以使用JUnit让您的测试更轻松。使用JUnit,您的测试可能如下所示:

public class PlayingCardsTest {
  private PlayingCards playingCards = new PlayingCards();

  @Test
  public void testAddCard() {
    playingCards.addCard(new Card());

    assertEquals(1, playingCards.size());
  }
}

然后,您将使用JUnitRunner运行JUnit测试。