• 用Eclipse进行单元测试JUnit4


    (1)在项目中引入Jar包

    (2)编写需要测试的类

    public class Calculator {
         private static int result=0; // 静态变量,用于存储运行结果
            public int add(int n) {
                result = result + n;
                return result;
            }
            public void substract(int n) {
                result = result - 1;  //Bug: 正确的应该是 result =result-n
            }
            public void multiply(int n) {
            }         // 此方法尚未写好
            public void divide(int n) {
                result = result / n;
            }
            public void square(int n) {
                result = n * n;
            }
            public void squareRoot(int n) {
              //  for (; ;) ;            //Bug : 死循环
            }
            public void clear() {     // 将结果清零
                result = 0;
            }
            public int getResult() {
                return result;
            }
    }

    (3)将鼠标点在要测试的类上单击->new->JUnit Test Case

    (4)勾选要测试的方法

    (5)测试方法生成

    (6)修改测试方法体

    public class CalculatorTest {

        @Before
        public void setUp() throws Exception {
        }

        @Test
        public void testAdd() {
            Calculator cal = new Calculator();
            int result = cal.add(5);
            Assert.assertEquals("加法有问题",5, result);
            //fail("Not yet implemented");
        }

        @Test
        public void testSubstract() {
            fail("Not yet implemented");
        }

        @Test
        public void testMultiply() {
            fail("Not yet implemented");
        }

        @Test
        public void testDivide() {
            fail("Not yet implemented");
        }

        @Test
        public void testSquare() {
            fail("Not yet implemented");
        }

        @Test
        public void testSquareRoot() {
            fail("Not yet implemented");
        }

        @Test
        public void testClear() {
            fail("Not yet implemented");
        }

        @Test
        public void testGetResult() {
            fail("Not yet implemented");
        }

    }
    (7)在生成的测试类的测试方法上单击->run as ->JUnit Test

  • 相关阅读:
    常用的ROS命令
    matlab练习程序(旋转矩阵、欧拉角、四元数互转)
    matlab练习程序(求向量间的旋转矩阵与四元数)
    matlab练习程序(点云表面法向量)
    matlab练习程序(点云下采样)
    matlab练习程序(局部加权线性回归)
    matlab练习程序(加权最小二乘)
    C#编程(五十七)----------位数组
    C#编程(五十六)----------可观察的集合ObservableCollection
    C#编程(五十五)----------HashSet和SortedSet
  • 原文地址:https://www.cnblogs.com/j-liu3323/p/6553524.html
Copyright © 2020-2023  润新知