Junit实例(计算加减乘除)

 

1、eclipse创建Java project,并建立相应的包、类(calculate.java)

2、在package explorer中右键new Junit Test Case,关联相应的工程

3、选择Junit4则会自动引入相应的包

4、编写calculate类中的加减乘除函数

package com.calculate;

public class Calculate {
    public int add(int a,int b)
    {
        return (a+b);
    };
    public int subtract(int a,int b)
    {
        return (a-b);
    };
    public int multiply(int a,int b)
    {
        return (a*b);
    };
    public int divide(int a,int b)
    {
        if(b==0)
        {
            System.out.print("分母不能为0");
            return 0;
        }
        else
        {
            
            return (a/b);
        }
        
    };
    
}

5、主函数main

package com.calculate;

public class test {
    public static void main(String[] args)
    {
        Calculate test=new Calculate();
        System.out.println("加法运算:"+test.add(12, 13));
        System.out.println("减法运算:"+test.subtract(18, 2));
        System.out.println("乘法运算:"+test.multiply(2, 6));
        System.out.println("除法运算:"+test.divide(4, 4));
    }
}

6、编写测试用例

package com.calculate;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class Calculatetest {
    Calculate mycal=new Calculate();
    @Before
    public void setUp(){
        System.out.println("测试开始");
    }
    @After
    public void down()
    {
        System.out.println("测试结束");
    }
    @Test
    public void testAdd() {
        assertEquals(8,mycal.add(2, 6));
    }
    @Test
    public void testsubtract() {
        assertEquals(2,mycal.subtract(4,2));
        assertEquals(7,mycal.subtract(9, 2));
    }
    @Test
    public void testmultiply() {
        assertEquals(15,mycal.multiply(3, 5));
        assertEquals(12,mycal.multiply(3, 4));
    }
    @Test
    public void testdivide() {
        assertEquals(1,mycal.divide(4, 4));
        assertEquals(0,mycal.divide(4, 0));
        assertEquals(2,mycal.divide(4, 2));
    }
}

7、右键工程->Run as->Junit Test,如果有错误则滚动条会出现红色,否则为绿色。

 

结束!

posted @ 2015-05-31 10:43  只如初见wmj  阅读(3010)  评论(0编辑  收藏  举报