Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a test class to test my code?

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");
    }
}
like image 338
user2022871 Avatar asked Mar 08 '13 19:03

user2022871


People also ask

How do you write a test class?

The test class are written under @isTest annotation. By using this annotation for test class we maintain code limit as it is not counted in it. Create Raw-Data At First: The Test Class In Apex Salesforce does not have access to any of the data which is stored in the related Salesforce org by default.

What is test class in testing?

Test classes are the code snippets which test the functionality of other Apex class. Let us write a test class for one of our codes which we have written previously. We will write test class to cover our Trigger and Helper class code. Below is the trigger and helper class which needs to be covered.


1 Answers

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));
  }
} 
like image 129
Avinash Singh Avatar answered Oct 21 '22 11:10

Avinash Singh