欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Junit测试实例1

程序员文章站 2022-04-29 19:22:22
...
[size=large]
Junit测试格言两则:
1)keep the bar green to keep the code clean!!!
2)单元测试不是证明您是对的,而是证明您没有错误!!!

被测试类代码
package com.zyg.test.junit3;
测试类代码
package com.zyg.test.junit3;
import junit.framework.Assert;
import junit.framework.TestCase;

/**
* junit3.8中测试类必须继承Test父类
* @author zyg
*/
public class CalculatorTest extends TestCase{
/**
* junit3.8中测试方法需要满足以下原则
* 1.public
* 2.void
* 3.无方法参数
* 4.方法名称必须以test开头
*/
public void testAdd(){
Calculator cal = new Calculator();
int result = cal.add(1, 2);

//断言
Assert.assertEquals(3,result);
}

public void testMinus(){
Calculator cal = new Calculator();
int result = cal.minus(1, 2);
Assert.assertEquals(-1, result);
}

public void testMultiply(){
Calculator cal = new Calculator();
int result = cal.multiply(2, 3);

//断言
Assert.assertEquals(6, result);
}

public void testDivide(){
Calculator cal = new Calculator();
int result = 0;
try {
result = cal.divide(6, 4);
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}

//断言
Assert.assertEquals(1,result);
}

public void testDivide2(){
Throwable tx = null;
try{
Calculator cal = new Calculator();
cal.divide(4, 0);

Assert.fail();
}catch(Exception ex){
tx = ex;
}
System.out.println(tx.getMessage());
Assert.assertNotNull(tx);
Assert.assertEquals(Exception.class, tx.getClass());
Assert.assertEquals("除数不能为零!!",tx.getMessage());
}
}
/**
* 数学计算
*
* @author zyg
*
*/
public class Calculator {

public int add(int a, int b) {
return a + b;
}

public int minus(int a, int b) {
return a - b;
}

public int multiply(int a, int b) {
return a * b;
}

public int divide(int a, int b) throws Exception{
if(0 == b){
throw new Exception("除数不能为零!!");
}
return a / b;
}
}
[/size]
相关标签: junit 单元测试