实现一个简单的计算
注:目标类和测试类要放在同一包下, JUnit单元测试基础要点
目标类:Calculator.java
- package com.junit3_8;
-
- public class Calculator {
-
- 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)throws Exception
- {
- if (0 == b)
- {
- throw new Exception("除数不能为0");
- }
- return a / b ;
- }
-
- }
测试类: CalculatorTest.java
- package com.junit3_8;
-
- import junit.framework.Assert;
- import junit.framework.TestCase;
-
- public class CalculatorTest extends TestCase{
-
- Calculator cal;
-
-
- public void setUp()
- {
-
-
- cal = new Calculator();
-
- }
-
-
- public void tearDown()
- {
-
- }
-
-
- public void testAdd()
- {
-
- int result = cal.add(1, 2);
-
- Assert.assertEquals(3, result);
-
- }
-
- public void testSubtract()
- {
-
- int result = cal.subtract(1, 2);
-
- Assert.assertEquals(-1, result);
-
- }
-
- public void testMultiply()
- {
-
- int result = cal.multiply(1, 2);
-
- Assert.assertEquals(2, result);
-
- }
-
- public void testDivide()
- {
- int result = 0;
-
- try
- {
- result = cal.divide(4, 2);
-
- }
- catch(Exception e)
- {
- e.printStackTrace();
-
- Assert.fail();
- }
-
- Assert.assertEquals(2, result);
-
- }
-
-
- public void testDivideByZero()
- {
- Throwable th = null ;
-
-
- try
- {
- cal.divide(1, 0);
- Assert.fail();
- }
- catch(Exception e)
- {
- th = e ;
-
- }
-
-
- Assert.assertNotNull(th);
-
- Assert.assertEquals(Exception.class, th.getClass());
- Assert.assertEquals("除数不能为0", th.getMessage());
-
- }
-
-
- public static void main(String[] args)
- {
-
- junit.textui.TestRunner.run(CalculatorTest.class);
-
-
-
-
-
-
- }
-
- }
1.调用 Assert.fail() 是让测试失败,该方法一般放在你认为不会到达的地方
2.这段代码让整个程序简便了许多 Calculator cal; //在“每个”测试方法执行之前被调用 public void setUp() { //这段代码在这写比较方便,只写一次就够, //不用在每个方法里写,因为这个方法每次都被调用,生成不同的对象,供测试方法使用 cal = new Calculator(); }
基于JUnit3.8的一个简单的测试程序
原文:http://www.cnblogs.com/hoobey/p/5293974.html