Java Reference
In-Depth Information
Figure 7.4 shows the result of running three tests named testAddComment , testIllegal-
Rating , and testInit , which are defined in the test class. The ticks immediately to the left
of the test names indicate that the tests succeeded. You can achieve the same result by selecting
the Test All option from the pop-up menu associated with the test class or running the tests indi-
vidually by selecting them from the same menu.
Test classes are clearly different in some way from ordinary classes, and if you open the source
code of SalesItemTest , you will notice that it has some new features. At this stage of the
book, we are not going to discuss in detail how test classes work internally, but it is worth not-
ing that although the source code of SalesItemTest could have been written by a person, it
was, in fact, automatically generated by BlueJ. Some of the comments were then added after-
wards to document the purpose of the tests.
Each test class typically contains tests for the functionality of its reference class. It is created
by using the right mouse button over a potential reference class and selecting Create Test Class
from the pop-up menu. Note that SalesItem already has a test class, so this additional menu
item does not appear in its class menu, but the one for Comment does have this option, as it cur-
rently has no associated test class.
The test class contains source code both to run tests on a reference class and to check whether
the tests were successful or not. For instance, here is one of the statements from testInit that
checks that the price of the item is 1000 at that point:
assertEquals(1000, salesIte1.getPrice());
When such tests are run, BlueJ is able to display the results in the window shown in Figure 7.4.
In the next section, we shall discuss how BlueJ supports creation of tests so that you can create
your own automated tests.
Exercise 7.13 Create a test class for the Comment class in the online-shop-junit project.
Exercise 7.14 What methods are created automatically when a new test class is created?
7.4.3
Recording a test
As we discussed at the beginning of Section 7.4, test automation is desirable because manu-
ally creating and re-creating tests is a time-consuming process. BlueJ makes it possible to
combine the effectiveness of manual unit testing with the power of test automation by enabling
us to record manual tests and then replay them later for the purposes of regression testing. The
SalesItemTest class was created via this process.
Suppose that we wanted to thoroughly test the addComment method of the SalesItem class.
This method, as we have seen, adds customer comments if they are valid. There are several tests
we would like to make, such as:
adding a first comment to an empty comment list (positive)
adding further comments when other comments already exist (positive)
 
Search WWH ::




Custom Search