• 【笔记】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 }
  • 相关阅读:
    第3章 对象基础
    [置顶] CSDN博客客户端(非官方)
    javascript 修改对象
    Print2Flash出现"System Error. Code:1722. RPC服务器不可用."错误解决办法
    ConfigHelper 配置文件辅助类
    多个委托方法的顺序执行
    javascript Table
    字符串拼接方式(待商榷)
    CSDN博客客户端(非官方)
    javascript 对象继承
  • 原文地址:https://www.cnblogs.com/halflife/p/2077687.html
Copyright © 2020-2023  润新知