up previous next contents
Next: Recap Up: JUnit Previous: Unit Testing with JUnit   Contents


A sample JUnit session

Let's go back to the need for a Pizza class. Here are the things we want to be able to do with our Pizza class.

  1. Create a means of adding toppings to a pizza.
  2. Create a Pizza class and a test class for it.
  3. Create methods to get the list of toppings from a pizza.
  4. Create a way to remove a topping from a pizza.
  5. Create a way to determine the price of a pizza.

For this class your first task is to make sure you can add and remove toppings. How do you start?

  1. First, make sure you have JUnit set up properly so you can easily use it.
  2. Next, create the desired Pizza class, but implement nothing.
  3. Next, create a test class named _Pizza. This class will extend TestCase, and will hold all of your unit tests for the Pizza class.
  4. In the _Pizza class, start to implement the first test method. The first thing I want to be able to do is to get a list of toppings that a pizza has, so I write a little code like this:
    public void testToppingsOnNewPizza()
    {
      Pizza pizza = new Pizza();
      List toppings = pizza.getToppings();
      assert( (toppings.size()==0) );
    }
    

  5. Run this JUnit test. Does it work?

  6. No, it doesn't work, because the getToppings() method does not exist. So what do you do next? Make it work. Implement this behavior in the Pizza class.

  7. Go to the Pizza class. Create a method named getToppings(). From what we know so far it should return a List, and apparently for a new Pizza(), the best thing to do is to return an empty List (not a null, but a List with nothing in it).

    public List getToppings()
    {
      return this.toppings;
    }
    

  8. Will this work by itself? No, you also have to have a List named toppings in the Pizza class. Here's what the Pizza class should look like:

    public class Pizza
    {
      private List toppings = new LinkedList();
    
      public List getToppings()
      {
        return this.toppings;
      }
    }
    

  9. Now run JUnit again ...does the test work?


Next: Recap Up: JUnit Previous: Unit Testing with JUnit   Contents