zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    模板方法模式
    策略模式
    享元模式
    组合模式
    桥接模式
    外观模式
    代理模式
    装饰者模式
    适配器模式
    类之间的关联关系和依赖关系
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9421061.html
Copyright © 2011-2022 走看看