How to write a test class to test my code?

user2022871 picture user2022871 · Mar 8, 2013 · Viewed 86k times · Source

I want a test class to test this class but i dont know how to write it and i tried to see online but i still couldnt figure it out.I wrote the code on BlueJ, i'm trying to create the set game.

import java.util.*;

public class Deck
{
    ArrayList<Card> deck;
    public Deck ()
    {
         deck = new ArrayList<Card>();
    }

     public Deck (int capacity)
    {
        deck = new ArrayList<Card>(capacity);
    }

    public int getNumCards ()
    {
        return deck.size();
    }

    public boolean isEmpty () 
    {
        return deck.isEmpty();
    }

    public void add (Card card) 
    {
        deck.add(0,card);
    }

    public Card takeTop() 
    {
        return deck.remove(0);
    }

    public void shuffle ()
    {
        Collections.shuffle(deck);
    }

    public void sort ()
    {
        Collections.sort(deck);
    }

    public String toString ()
    { 
         return (deck.toString()+ "\n");
    }
}

Answer

Avinash Singh picture Avinash Singh · Mar 8, 2013

First you need to decide on the what test cases you need to write for your class , You can use a library like Junit to create test cases once you have the test case list handy.

Here is an example of a few Junit methods

import static org.junit.Assert.assertEquals;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class MyClassTest {

  MyClass tester;

  @BeforeClass
  public static void testSetup() {
    tester = new MyClass();
  }

  @AfterClass
  public static void testCleanup() {
    // Do your cleanup here like close URL connection , releasing resources etc
  }

  @Test(expected = IllegalArgumentException.class)
  public void testExceptionIsThrown() {        
    tester.divide(1000, 0);
  }

  @Test
  public void testMultiply() {
    assertEquals("Result", 50, tester.multiply(10, 5));
  }
}