An Introduction to Testing
In this lesson, we will develop a program and show how testing discovers logical errors.
We'll cover the following
A Problem solved: The café sign
The cafés in a certain franchise all operate on the same meal schedule but have their own names. We have been employed to write the software for an electronic sign that displays the name of the café, whether it is open or closed, and the current meal served, if any. The meal schedule is as follows:
- 6 a.m. to 10 a.m. Breakfast
- 11 a.m. to 2 p.m. Lunch
- 5 p.m. to 8 p.m. Dinner
- Any other time Closed
Discussion
We must be able to access the current time so that we can create a suitable message for the sign. Recall from an earlier chapter, we introduced the standard class LocalTime
, which is in the package java.time
. If the statement:
LocalTime time = LocalTime.now(ZoneId.of("America/New_York"));
executes, the expression time()
will return a string such as
"16:19:38"
.
During talks with the franchise owner, we have designed the sign’s message. When Café Java
is open for lunch, for example, its sign will display the following message:
Café Java
OPEN
Serving Lunch until 2 p.m.
The time now is 11:45
A few hours later, when the café is closed, the sign will display the following message:
Café Java
CLOSED
See you at 5 p.m.
The time now is 15:00
Since LocalTime
uses a 24-hour notation for the time of day, we will use the same notation for now on the last line of our sign. To simplify our first solution even further, we can omit the third line, indicating the time that the café will reopen, from the message when the café is closed.
A trial program
Temporarily ignoring certain requirements in a problem statement by omitting features from our initial solutions is a wise plan. Writing one or more short programs to try out our ideas is another good strategy. So before we tackle our simplified problem statement, let’s write some code that gets the time of day and identifies the meal, if any, being served at that time. If you did Challenge 3 in the previous chapter, you’ve already given some thought to this identification task.
Here is some pseudocode that describes the steps we can take:
Get a LocalTime
object
Extract the hour from the LocalTime
object
if (
it is breakfast time)
return
“Breakfast”
else if (
it is lunchtime)
return
“Lunch”
else if (
it is dinnertime)
return
“Dinner”
else
return
“Closed”
The program given below translates this pseudocode into the public method getMealServed
. Run the program and check your results against the actual time of day.
Get hands-on with 1400+ tech skills courses.