public class Calculator {
public int Jia(int a,int b){
return a+b;
}
public int Jian(int a,int b){
return a-b;
}
public int Cheng(int a,int b){
return a*b;
}
public int Chu (int a,int b) throws Exception{
if(b==0){ throw new Exception("除数不能为0");}
return a/b;
}
}
import junit.framework.Assert;
import junit.framework.TestCase;
public class CalculatorTest extends TestCase {
Calculator cl=new Calculator();
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testJia() {
int result;
result = cl.Jia(3, 2);
Assert.assertEquals(5, result);
}
public void testJian() {
int result;
result = cl.Jian(6,3);
Assert.assertEquals(3, result);
}
public void testCheng() {
int result;
result = cl.Cheng(2,3);
Assert.assertEquals(6, result);
}
public void testChu() throws Exception {
int result;
result = cl.Chu(6,3);
Assert.assertEquals(2, result);
try
{
result =cl.Chu(4,0);
}
catch(Exception ex){
assertEquals("除数不能为0!", ex.getMessage());
fail("除数不能为0");
}
}
}
转载请注明:天狐博客 » junit单元测试java加减乘除程序(除数为0异常处理)