2017-12-06 13 views
0

私はクラスの使用を通してJavaでカードゲームをコーディングしようとしています。メソッドの結果を検証するテストクラスを作成するだけでなく、テストが失敗したかどうかを示すバナーを印刷し、すべてのテストが合格したか失敗したかを確認する最終バナーを出力する必要があります。トランプカードのセットを確認できるテストクラスを作成するにはどうすればよいですか?

トランプクラス(このクラスは、テスターに​​行われる必要がある)

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

答えて

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

あなたは、新しいPlayingCardsTestを作成し、各テストメソッドを呼び出しますmainを作成することができます。

また、JUnitを使用すると、テストをはるかに簡単にすることができます。そして、あなたがJUnitRunnerであなたのJUnitテストを実行します

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

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

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

:JUnitのでは、あなたのテストは、次のようになります。

関連する問題