如下所示,先通过 build path 导入 junit 环境依赖的 jar 包:


这里写图片描述

1. junit.framework.*

  • junit.framework.* 主要类和函数:
    • Test
    • TestCase
    • TestSuite

实现并运行(run as => Java Application,因其有 java 应用所需的入口函数:main 函数)如下的代码:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;

public class FileReaderTester extends TestCase
{
    private FileReader input = null;

    public FileReaderTester(String name)
    {
        super(name);
    }

    protected void setUp()
    {
        try
        {
            input = new FileReader("data.txt");
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
    }

    public void testRead() throws IOException
    {
        char ch = '&';
        for (int i = 0; i < 4; ++i)
        {
            ch = (char)input.read();
        }
        assertEquals('d', ch);
    }

    protected void tearDown()
    {
        try
        {
            input.close();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static Test suite()
    {
        TestSuite suite = new TestSuite();
        suite.addTest(new FileReaderTester("testRead"));
        return suite;
    }

    public static void main(String[] args)
    {
        TestRunner.run(suite());
    }

}

2. org.junit.*

  • 待测试的功能类的工作,不依赖任何相关的测试类;
    • 可以独立运行;
    • 测试类的对象则是待测试的功能类;
    • 测试类构造的用例是为了保证待测试的功能类能够如期望的那样运行;
    • 测试类构造用例的对象是功能类的某一成员函数

这种类库层级形式,一般是通过 eclipse 界面操作完成的:

  • 完成功能类的开发;
  • 右键此待测类:
    • new => JUnit Test Case,选择 setUp, tearDown 等上下文函数;
    • next => 勾选待测类中的待测函数;
  • eclipse 自动生成相关代码;
  • 右键 run as => Junit Test

3. references

posted on 2018-01-19 00:37  未雨愁眸  阅读(792)  评论(0编辑  收藏  举报