在Eclipse中使用JUnit进行单元测试

如何编写测试代码肯定是开发人员最头疼的。JUnit是一个非常强大的单元测试包,可以对一个/多个类的单个/多个方法测试,还可以将不同的TestCase组合成TestSuit,使测试任务自动化。


本文简单介绍如何在eclipse中使用JUnit创建一个TestCase来测试一个简单的类。


我们写一个要测试的类Simple如下:



package jexi.test;
public class Simple {
    private int n;
    public Simple(int n) {
        this.n = n;
    }
    // 返回绝对值:
    public int foo() {
        return n>0 ? n : (-n);
    }
}


foo()方法返回绝对值,下一步,我们准备用JUnit对这个foo()方法进行全面测试。


首先,在eclipse中,创建一个java工程,把plugins\org.junit_3.8.1\junit.jar包含进去:


然后写好Simple.java,为它创建一个JUnit Test Case:



在弹出的对话框中填入测试类的名字:SimpleTest,勾上setUp():



编写测试代码:



package jexi.test;
import junit.framework.TestCase;

public class SimpleTest extends TestCase {
    private Simple s1, s2;

    protected void setUp() throws Exception {
        super.setUp();
        s1 = new Simple(10);
        s2 = new Simple(-7);
    }

    public void testFoo() {
        assertTrue(s1.foo()==10);
        assertTrue(s2.foo()==7);
    }
}


其中setUp()方法是构造初始化环境,我们在setUp中创建两个Simple的实例,testFoo()是用来测试foo()的测试方法,总是以test+方法名构成,然后在测试方法中测试:s1.foo()==10,如果返回值与期待的结果10相等,assertTrue()就执行成功,我们现在可以运行Run->Run As...->JUnit Test,左侧会显示测试结果:



如果我们把Simple的foo()方法改成:


    public int foo() {
        return n;
    }


再次运行JUnit Test,现在assertTrue(s2.foo()==7);测试结果就不正确了,JUnit会报告哪一行结果不正确:



双击就可以快速定位到测试失败的方法调用上。


总结


JUnit功能非常强大,是代码质量的可靠保证。精心设计的TestCase可以反复使用,将来对某个类进行了更改,只需要运行一遍TestCase就知道改动对客户端有无影响。若干个TestCase还可以组合成TestSuit,结合Ant使得编译,测试,运行整个过程自动化,只需要查看测试结果就可以知道哪些代码出了问题。

About this Entry

This page contains a single entry by Sky published on September 22, 2005 3:13 PM.

状态模式之星际应用 was the previous entry in this blog.

Eclipse使用技巧 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.