• eclipse 环境 JUnit 测试框架(junit.framework.* 与 org.junit.*)


    如下所示,先通过 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

  • 相关阅读:
    97. Interleaving String
    96. Unique Binary Search Trees
    95. Unique Binary Search Trees II
    94. Binary Tree Inorder Traversal
    odoo many2many字段 指定打开的form视图
    docker sentry 配置文件位置
    postgres 计算时差
    postgres 字符操作补位,字符切割
    postgres判断字符串是否为时间,数字
    odoo fields_view_get
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9421061.html
Copyright © 2020-2023  润新知