CourseReportTest


In CourseReportTest, modify the assertion in testReport to ensure that you produce the report in sorted order. Your test data currently takes only the department into account. That's fine for now:

 assertEquals(       "CZEC 200" + NEWLINE +       "ENGL 101" + NEWLINE +       "ITAL 410" + NEWLINE,    report.text()); 

The test fails as expected. You should be able to see in JUnit that the sessions are in the wrong order.

To solve the problem, use Collections.sort to order the sessions list.

 public String text() {    Collections.sort(sessions);    StringBuilder builder = new StringBuilder();    for (CourseSession session: sessions)       builder.append(          session.getDepartment() + " " +          session.getNumber() + NEWLINE);    return builder.toString(); } 

Unfortunately, this will not compile:

 cannot find symbol symbol  : method sort(java.util.List<sis.studentinfo.CourseSession>) location: class java.util.Collections       Collections.sort(sessions);                  ^ 

The source of the error can be difficult to decipher, even if you are relatively experienced in Java. The problem is that the method declaration for sort requires the objects it sorts to be of the type java.lang.Comparable. (How it does that involves advanced syntax that I will discuss in Lesson 14 on generics.)

Comparable is a type that allows you to compare objects to one another. But you want to compare CourseSession objects, since that's what you bound the variable sessions to. The secret to getting this to work takes advantage of a feature in Java known as interfaces. Interfaces allow an object to act as more than one type. You will modify CourseSession to act as a java.lang.Comparable type in addition to being a CourseSession.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net