up previous next contents index
Next: Other notes Up: Working Backwards with JUnit Previous: How to do Unit   Contents   Index


An example

Your next assignment is to create a Pizza class. 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?


up previous next contents index
Next: Other notes Up: Working Backwards with JUnit Previous: How to do Unit   Contents   Index