Docsity

TDD Implementation of Song Class in Cashless Jukebox Project for C Sc 335, Spring 2007, Assignments of Computer Science

Toggle sidebar
bg1
Software Design using Test
Driven Development (TDD)
Goals
Consider one way to develop software
Become familiar with Test Driven Development
Learn how to use some of JUnit
Experience refactoring
Iterative Development
Recently industry and academia have been adopting an agile approach to software development,
implying less emphasis on documentation. Agile processes still have analysis, design, coding,
testing, and documentation; however these methods emphasize working software as the primary
measure of progress. Software developers work with customers—those wanting the software— in
order to prioritize what is most important. Developers code and test to get those features. Design
is employed, but throughout the whole process. Testing is done, but it is done all along.
The software development technique of TDD
is demonstrated here in the context of building
the Song class for the Cashless Jukebox Project
#2 for C Sc 335, Spring 2007.
The rules of TDD
1. Write the tests first with assertions that indicate the desired behavior.
2. Run the tests to see the new test fail.
3. Write code that makes the test pass.
4. Refactor (makes small changes to code to improve it)
The classes in this chapter will be developed with the aid of the JUnit testing framework
developed by Erich Gamma and Kent Beck. JUnit is a design and testing tool that is part of
virtually all Java integrated development environments (IDE’s). This includes IDEs designed for
introductory course such as BlueJ or Dr Java. It also includes IDEs for professional software
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download TDD Implementation of Song Class in Cashless Jukebox Project for C Sc 335, Spring 2007 and more Assignments Computer Science in PDF only on Docsity!

Software Design using Test

Driven Development (TDD)

Goals

Consider one way to develop software

 Become familiar with Test Driven Development

 Learn how to use some of JUnit

 Experience refactoring

Iterative Development

Recently industry and academia have been adopting an agile approach to software development,

implying less emphasis on documentation. Agile processes still have analysis, design, coding,

testing, and documentation; however these methods emphasize working software as the primary

measure of progress. Software developers work with customers—those wanting the software— in

order to prioritize what is most important. Developers code and test to get those features. Design

is employed, but throughout the whole process. Testing is done, but it is done all along.

The software development technique of TDD

is demonstrated here in the context of building

the Song class for the Cashless Jukebox Project

#2 for C Sc 335, Spring 2007.

The rules of TDD

1. Write the tests first with assertions that indicate the desired behavior.

2. Run the tests to see the new test fail.

3. Write code that makes the test pass.

4. Refactor (makes small changes to code to improve it)

The classes in this chapter will be developed with the aid of the JUnit testing framework

developed by Erich Gamma and Kent Beck. JUnit is a design and testing tool that is part of

virtually all Java integrated development environments (IDE’s). This includes IDEs designed for

introductory course such as BlueJ or Dr Java. It also includes IDEs for professional software

C Sc 335

developers such as NetBeans, IntelliJ, and Eclipse. Other testing frameworks that aid software

development also exist for designing and testing software in other popular programming

languages such as PHP, C++, C#, and VB.NET.

Develop (design and test) One Class, One Method at a Time

I will be specifying functionality as JUnit tests. The minimal code needed to write tests begins as

a new class named SongTest. To gain access to this testing and development tool, two imports

from the org.junit package are needed: Assert and Test.

import static org.junit.Assert.; import org.junit.Test; public class SongTest { }*

Self-Check

1. It helps to type in the code as you are reading. If you are new to Eclipse, ask your section

leader or a classmate on how to start Eclipse and create a new Java project.

These self-checks ask you to type in new code encountered in the reading. I indicate the

new code to be added in boldface within the gray background (as in all of the above). Begin

with the unit test named SongTest started above and type in the code as you encounter it. In

Eclipse, select File > New > JUnit Test Case and name it SongTest. If asked to add the

JUnit libraries, choose JUnit 4.0. After you type in the code above (or you have copied and

pasted it), you may see warnings because neither the imported Test or static methods of

org.junit.Assert have been used yet.

1. Write the Test

To allow users to identify the song they want to play, we'll begin with making sure each Song can

remember its own title and artist. First, let's set up the test.

The JUnit testing framework version 4.0 uses the @Test annotation to mark a method as a

test. You must declare a method as public, with a return type of void (which means the method

returns nothing). Because older versions of JUnit required that the test method name must begin

with the letters test, the method names will begin with test (it's an old habit). Here is one valid

test method written as a stub (no code is yet in the body of the method):

@Test public void testGetters() { }

Self-Check

2 Add the test method above to SongTest.

C Sc 335

2. Make the test fail

To make the test fail, the code must compile. The following minimal Song class removes the

compile-time errors as long as a newly designed constructor is included. The method names,

parameters and return type must match.

public class Song {

public Song(String songArtist, String songTitle) { } public String getTitle() { return null; } public String getArtist() { return null; } }

Self-Check

5 Create a new class named Song and add the constructor and the two methods as shown above.

You can return any string for getTitle and getArtist (I chose to return null as would

Eclipse if you let Eclipse write the code for you)

Now running the unit test will show that the getTitle() method does not return the correct

value (no surprise). We expected the string value "Help", however the actual value intentionally

returned from the method is null (this Mac screenshot may differ, but the content is the same).

With compile-time errors fixed and the test failing, I now want to make the tests pass.

3. Makes the test pass

We need a way for every Song object to remember its own artist and title. Different instances of

the same class remember their own state through instance variables. Specifically, adding a title

instance variable to the Song class allows many Song objects to have their own titles. The

constructor must also assign the argument to the correct instance variable. Additionally,

re

d

ba

r

Using TDD to Design class Song

getTitle()must return that remembered value. These changes are shown below in the updated

Song class that will make both assertions pass (thus, you should see the green bar in JUnit).

public class Song { // Instance variables to remember the artist and title private String artist; private String title; public Song(String songArtist, String songTitle) { // Let each object remember these values artist = songArtist; title = songTitle; } public String getTitle() { return title; } public String getArtist() { return artist; } }

Self-Check

6 For the remainder of this chapter, add the highlighted code. There will be no more explicit self-

checks. After adding the six highlighted lines of code to class Song as shown above, you should

see the tests pass.

Play a Song Only Five Times per Day

One of the requirements for this Jukebox system maintains that no song should be played more

than five times on a given date. One way to manage this is to have each Song correctly respond

true or false when asked if it can be played today. This means we are making the Song

responsible for this feature.

1. Write the test

gree

n

bar

Using TDD to Design class Song

songsPlayedToday = 0;

public boolean canPlayToday() {

return songsPlayedToday < MAX_SONGS_PER_DAY;

Now the new test will pass. I am obviously not done. What happens if a song has been played 5

times on the date it gets asked to canPlayToday? I write a test to describe what should happen.

1. Write the Test

Because some method is needed to let the Song know that it has been played, this test shows a

need for a new method named recordOnePlay.

@Test public void testCanPlayTodayWithUpTo5Plays() { Song aSong = new Song("Beatles", "Help"); aSong.recordOnePlay(); assertTrue(aSong.canPlayToday()); aSong.recordOnePlay(); assertTrue(aSong.canPlayToday()); aSong.recordOnePlay(); assertTrue(aSong.canPlayToday()); aSong.recordOnePlay(); assertTrue(aSong.canPlayToday()); aSong.recordOnePlay(); // This song has been played 5 times already assertFalse(aSong.canPlayToday()); }

The assertions above suggest what should happen during the messages: canPlayToday returns

true until there have been five recordOnePlay messages. Some other object will likely use

these two new methods to either help play the Song or to notify the user that the Song has been

played its maximum number of times.

2. Make the test fail

First get the code to compile by adding recordOnePlay to Song. Since recordOnePlay is a

void method, it need not return a bogus value to make the test fail.

public void recordOnePlay() { }

C Sc 335

3. Make the test pass

Without any thought about the day upon which the Song was played, we can get canPlayToday

working (test passes) by incrementing the instance variable that keeps track of how often the song

has been played inside this new recordOnePlay method.

public void recordOnePlay() {

songsPlayedToday++;

However, this will do precisely what the name implies. Keep track of how often this song has

been played at any time since the Song was constructed. This may be good for a top ten list, but

as the name of the instance variable suggests, songsPlayedToday does not yet do what its

name reveals it should do. songsPlayedToday must maintain a number that starts at 0 at

midnight and gets up to 5 maximum during the same calendar date. Just adding 1 to

songsPlayedToday every time won't do this. We need to consider the calendar date when the

canPlayToday() message is actually sent and the days on which the song was played in the past.

One solution is to keep a list of all dates upon which the song was played. This requires a

way to store the list of dates, a way to add to the list during recordOnePlay(), and an algorithm

to find all dates in the list that match the date the message is sent. We can use an array to store all

dates upon which a Song played. Instead of developing a whole new type for managing dates,

we'll use the existing java.util.GregorianCalendar.

GregorianCalendar

A GregorianCalendar object allows programmers to store dates in a culture that uses the

Gregorian calendar instituted in October 15, 1582 under Pope Gregory. To demonstrate, here is

some code that constructs an empty array and adds three GregorianCalendar objects.

// Create an empty list that can store GregorianCalendar objects GregorianCalendar[] datesPlayed = new GregorianCalendar[5]; int n = 0; // Add 3 dates objects as set in the computer's clock datesPlayed[n] = new GregorianCalendar(); n++; datesPlayed[n] = new GregorianCalendar(); n++; datesPlayed[n] = new GregorianCalendar();

The for loop prints the getTime() version of each GregorianCalendar object reference at

indexes 0, 1, and 2 of datesPlayed. The getTime() method returns a string with the time and

date when the GregorianCalendar object was constructed.

for (int index = 0; index < 3; index++) { System.out.println(datesPlayed[index].getTime()); } Fri Aug 11 19:46:35 MST 2006 Fri Aug 11 19:46:35 MST 2006 Fri Aug 11 19:46:35 MST 2006

C Sc 335

The new method getTimesPlayedToday() has a rather bizarre way to see if one dates "equals"

another. This is necessary because the equals method for GregorianCalendar returns false if

two different GregorianCalendar objects differ by as little as 1 millisecond.

public boolean equals (Object obj) Compares this GregorianCalendar to the specified Object. The result is true if and only if the argument is a GregorianCalendar object that represents the same time value (millisecond offset from the Epoch) under the same Calendar parameters and Gregorian change date as this object.

Therefore the dates in the array are compared to current year, month, and day using get

messages. A get message is return the value of one of many fields for the object

public int get (int field)

Returns the value of the given calendar field.

The java.util.Calendar class declares over 60 fields declared as class constants that can be

used in the get method such as these:

Calendar.DAY_OF_MONTH

Field number for get and set indicating the day of the month.

Calendar.HOUR

Field number for get and set indicating the hour of the morning or afternoon.

Calendar.MILLISECOND

Field number for get and set indicating the millisecond within the second.

If these three fields are the same as today's year, month and day, then the array value "equals" the

current date (actually there are simpler ways, but let's move on).

This new test still passes. This first attempt may appear to work—you get the green bar.

However the list will grow to 5 larger at another recordOnePlay message. At that time, there will

be an attempt to add to a filled array.

Using TDD to Design class Song

We could declare the array to be bigger, say 10, or maybe 100, or maybe the number of times any

one song could be played. But this is difficult to say. I will arbitrarily pick 750.

datesPlayed = new GregorianCalendar[ 750 ];

Eventually, the list will contain GregorianCalendar objects from many different dates (assuming

users are actually selecting that song). But what happens if one song gets played more than 750

times? And do we need to really store more than the most recent 5 dates? Won’t 5 do? Or is there

an easier way?

Refactoring

Refactoring is a term applied to making small changes to existing code that does not change its

behavior. Refactorings are intended to make the code more readable; easier to understand, and

easier to maintain. There currently exists a long complicated boolean expression in

getTimesPlayedToday(). To maker the code more readable, we could do a refactoring known as

extract method. Here is the desired change made to the method.

// Let someone know how many times this Song has played on the current date private int getTimesPlayedToday() {

re

d

ba

r

Using TDD to Design class Song

Challenge (if time permits, if not, do this part after section and before

you turnin iteration 1)

Modify the Song class to be more efficient with cleaner code that is easier to read, and of course

still work.

1. Use the algorithm above

2. Eliminate the array in Song

3. And of course, run your unit test