BlueJ also features support for testing. We will write a new method and test that it works. Add the following method to the Cat class:
public boolean isHappy()
{
return false;
}
Next, we need a test class. If you right-click on the Cat class you will see that the bottom option is "Create Test Class". Click on this, and you will see that a new green class called CatTest appears next to the Cat class. Test classes are green in BlueJ.
You can add a test by writing code in the CatTest class. But BlueJ also allows you to create tests interactively, which we will do now. Right-click on the CatTest class (note: CatTest, not Cat) and select "Create Test Method...". A dialog will pop up to ask for a name: call it testHappy and then press OK. BlueJ then switches into recording mode: you will see that a new set of controls appears on the left hand side of the main window, including a red recording indicator.
Create a new Cat object, by right-clicking the Cat class and selecting "new Cat()" as before. Then right-click on the cat1 object, and call the "boolean isHappy()" method. You will see that this time, the result dialog has an extra section at the bottom, asking if you want to add an assertion (a check). We want to check that the cat is not happy after creation, so we fill in false in the bottom-right value field and click Close.
Next, we right click the cat1 object and call the "void feed()" method. (Note: you'll need to have added the feed method as shown in part 3.) Then call the isHappy() method again. This time, fill in true in the bottom-right value field, as the intended behaviour is that the cat becomes happy after feeding. Then click Close.
Our test is now finished, so on the left-hand side of the BlueJ window, click the End button.
If you just want to run the individual test, you can right-click the individual test class and run the individual test method. More often though, you will want to run all tests. To do this, click the Run Tests button on the left-hand side of the main window. This will bring up the test results window, showing which tests pass and fail. Currently, our test fails, so the middle bar is red.
If you click on testHappy in the top list of tests, you can see the reason for this. To get more information, click the Show Source button. This will show the CatTest class source code, and highlight the line where the test failed. You can see that the problem is that the happy state is false after the feeding. That's because our happy method always returns false. Return to the source for the Cat class (not the CatTest class), and change the line inside the method to be as follows:
public boolean isHappy()
{
return fed;
}
Now go back to the BlueJ main window, click Compile and then click the Run Tests button again. This time, the test should pass and the bar should turn green.