zoukankan      html  css  js  c++  java
  • 个人项目 Individual Project

     github地址:   https://github.com/yranqiu/Individual-Project-1/blob/master/CalculatorTest

    编写一个Calculator类,这是一个能够简单实现加减乘除、平方、开方的计算器类,然后对这些功能进行单元测试。

    package andycpp;

    public class Calculator {
        private static int result; // 静态变量,用于存储运行结果
        public void add(int n) {
            result = result + n;
        }
        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;
        }
    }

    JUnit4单元测试包引入这个项目

     


    在弹出的属性窗口中,首先在左边选择“Java Build Path”,然后到右上选择“Libraries”标签,之后在最右边点击“Add Library…”按钮,




    然后在新弹出的对话框中选择JUnit4并点击确定,如上图所示,JUnit4软件包就被包含进这个项目了。

       生成JUnit测试框架:在EclipsePackage Explorer中用右键点击该类弹出菜单,选择“New à JUnit Test Case”。如下图所示:


    在弹出的对话框中,进行相应的选择


        点击“下一步”后,系统会自动列出你这个类中包含的方法,选择你要进行测试的方法。此例中,我们仅对“加、减、乘、除”四个方法进行测试。

    完整的CalculatorTest代码如下:

     

    package andycpp;

    import static org.junit.Assert.*;
    import org.junit.Before;
    import org.junit.Ignore;
    import org.junit.Test;

    public class CalculatorTest {

        private static Calculator calculator = new Calculator();
        
        @Before
        public void setUp() throws Exception {
            calculator.clear();
        }

        @Test
        public void testAdd() {
            calculator.add(2);
            calculator.add(3);
            assertEquals(5, calculator.getResult());
        }

        @Test
        public void testSubstract() {
            calculator.add(10);
            calculator.substract(2);
            assertEquals(8, calculator.getResult());
        }

        @Ignore("Multiply() Not yet implemented")
        @Test
        public void testMultiply() {
        }

        @Test
        public void testDivide() {
            calculator.add(8);
            calculator.divide(2);
            assertEquals(4, calculator.getResult());
        }
    }

    运行结果如下:

     

     

     总结:通过这个实验,了解一些软件测试的基本含义,学会了一些基本测试的步骤的设计和用例的构造。初步学会了junit4的使用,了解到基本流程和实现。

  • 相关阅读:
    react-路由简单封装
    promise 和 async / await
    数据结构 栈 、 队列 、 链表
    ES6 Symbol
    react-react常用包与对应使用
    node-egg的使用
    自我理解与概述-BFC(Block formatting context)
    Git
    MySQL优化技巧
    Shiro
  • 原文地址:https://www.cnblogs.com/yanyuranqiu/p/4459786.html
Copyright © 2011-2022 走看看