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

  • 相关阅读:
    java.util.ConcurrentModificationException 异常问题详解
    java1.8新特性整理(全)
    理解serialVersionUID是什么?有什么用?如何生成?
    数据结构与算法--->基础篇冒泡,选择,插入,希尔
    学习Java的第二天
    学习Java的第一天
    SpringBoot(2)—使用小技术总结
    SpringBoot(1)—相关工具使用
    json工具类(二)——google包
    json工具类(一)——alibaba包
  • 原文地址:https://www.cnblogs.com/j-liu3323/p/6553524.html
Copyright © 2011-2022 走看看