Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1937866
  • 博文数量: 606
  • 博客积分: 9991
  • 博客等级: 中将
  • 技术积分: 5725
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-17 19:07
文章分类

全部博文(606)

文章存档

2011年(10)

2010年(67)

2009年(155)

2008年(386)

分类: Java

2008-07-17 21:47:55


编码原则:
        从技术上强制你先考虑一个类的功能,也就是这个类提供给外部的接口,而不至于太早陷入它的细节。这是面向对象提倡的一种设计原则。
如果你要写一段代码:
1. 先用 junit 写测试,然后再写代码
2. 写完代码,运行测试,测试失败
3. 修改代码,运行测试,直到测试成功
编写步骤:如下图

测试代码:
package yhp.test.junit;

import junit.framework.*;
public class TestCar extends TestCase {
    protected int expectedWheels;
    protected Car myCar;
    public TestCar(String name) {
        super(name);
    }
    protected void setUp(){  //进行初始化任务
        expectedWheels = 4;
        myCar = new Car();
    }
    public static Test suite()    {//JUnit的TestRunner会调用suite方法来确定有多少个测试可以执行
        return new TestSuite(TestCar.class);
    }
    public void testGetWheels(){//以test开头,注意命名
        assertEquals(expectedWheels, myCar.getWheels());
    }
}

以下是通过eclipse自带的junit工具产生的代码:
package yhp.test.junit;
import junit.framework.TestCase;
public class TestCar2 extends TestCase {
    protected int expectedWheels;
    protected Car myCar;
    public static void main(String[] args) {
        junit.textui.TestRunner.run(TestCar2.class);//TestCar是个特殊suite的静态方法
    }
    protected void setUp() throws Exception {
        super.setUp();
        expectedWheels = 4;
        myCar = new Car();
    }
    protected void tearDown() throws Exception {
        super.tearDown();
    }
    public TestCar2(String arg0) {
        super(arg0);
    }
    public final void testGetWheels() {
        assertEquals(expectedWheels, myCar.getWheels());
    }
}

当有多个测试类的时候,系统能进行统一测试,这时可以利用TestSuite来实现。可以将TestSuite看作是包裹测试的一个容器。
通过eclipse自带的工具生成的代码如下:
package yhp.test.junit;
import junit.framework.Test;
import junit.framework.TestSuite;

public class AllTests {
     public static Test suite() {
        TestSuite suite = new TestSuite("Test for yhp.test.junit");
        //$JUnit-BEGIN$
        suite.addTest(TestCar.suite());         //调用的方法,参数不一样,实际是一致的。
        suite.addTestSuite(TestCar2.class);  //
        //$JUnit-END$
        return suite;
    }
}

阅读(986) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~