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.
- Create a means of adding toppings to a pizza.
- Create a Pizza class and a test class for it.
- Create methods to get the list of toppings from a pizza.
- Create a way to remove a topping from a pizza.
- 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?
- First, make sure you have JUnit set up properly so you can easily use it.
- Next, create the desired Pizza class, but implement nothing.
- Next, create a test class named _Pizza. This class will extend TestCase, and will hold all of your unit tests for the Pizza class.
- 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) );
}
- Run this JUnit test. Does it work?
- 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.
- 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;
}
- 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;
}
}
- Now run JUnit again ...does the test work?
Next: Recap
Up: JUnit
Previous: Unit Testing with JUnit
  Contents
|
|