【笔记】Eclipse and Java for Total Beginners—006

Lesson 06 – Using Test-First Development in Eclipse

  • Use test-first approach to write the Person toString() method
  • Method overriding
  • Field Hiding

1. toString() method

  • inherited from Object class
  • returns a String representation of the object
  • normally create for every class

2. Test-driven development

  • Think about what the method should do.
  • Write a test case that will test this method.
  • Write the new method.
  • Test the new method.
  • when it passes.. we’re done!

3. Test-driven development benefits

  • Forced to create detailed specifications before coding.
  • Test method serves as specification, documentation, and as unit test.
  • When method passes the test, method is complete and correct.
1 package org.totalbeginner.tutorial;
2
3  import org.totoalbeginner.tutorial.Person;
4
5  import junit.framework.TestCase;
6
7  public class PersonTest extends TestCase {
8
9 public void testPerson() {
10 Person p1 = new Person();
11 assertEquals("unknown name", p1.getName());
12 assertEquals(3, p1.getMaximumBooks());
13 }
14
15 public void testSetName() {
16 Person p2 = new Person();
17 p2.setName("Fred");
18 assertEquals("Fred", p2.getName());
19 }
20
21 public void testSetMaximumBooks() {
22 Person p3 = new Person();
23 p3.setMaximumBooks(10);
24 assertEquals(10, p3.getMaximumBooks());
25 }
26
27 public void testToString() {
28 Person p4 = new Person();
29 p4.setName("Fred Flintstone");
30 p4.setMaximumBooks(7);
31 String testString = "Fred Flintstone (7 books)";
32 assertEquals(testString, p4.toString());
33 }
34
35 }
1 package org.totoalbeginner.tutorial;
2
3  public class Person {
4
5 // fields
6 private String name; // name of the person
7 private int maximumBooks; // most books the person can check out
8
9 // constructors
10 public Person() {
11 name = "unknown name";
12 maximumBooks = 3;
13 }
14
15 // methods
16 public String getName() {
17 return name;
18 }
19
20 public void setName(String anyName) {
21 name = anyName;
22 }
23
24 public int getMaximumBooks() {
25 return maximumBooks;
26 }
27
28 public void setMaximumBooks(int maximumBooks) {
29 this.maximumBooks = maximumBooks;
30 }
31
32 public String toString() {
33 return this.getName() + " (" + getMaximumBooks()
34 + " books)";
35 }
36
37 }

posted on 2011-06-10 15:32  yf.x  阅读(233)  评论(0)    收藏  举报

导航