junit3.8例子

Java代码 复制代码

  

package org.test;
package org.test;

import junit.swingui.TestRunner;

public class Add {
	
	public int add(int a,int b){
		return a+b;
	}
	
	public static void main(String[] args){
		TestRunner runner = new TestRunner();
		runner.run(AddTest.class);
	}

}



Java代码 复制代码

 

package org.test;

import junit.framework.Assert;
import junit.framework.TestCase;

public class AddTest extends TestCase {
	
	private Add add = null;
	 
	@Override
	protected void setUp() throws Exception {
		add = new Add();
	}

	/**满足条件
	 * 1)必须是public
	 * 2)必须是void
	 * 3)必须以test开头
	 * 4)必须无参数
	 */
	public void testAdd(){
		int result = add.add(3, 5);
		Assert.assertEquals(8, result);
	}

}


Java代码 复制代码

 

package org.test;

public class Divide {
	
	public int divide(int a,int b) throws Exception{
		if(0 == b){
			throw new Exception("除数不能为0");
		}
		return a/b;
	}

}


Java代码 复制代码

 

package org.test;

import junit.framework.Assert;
import junit.framework.TestCase;

public class DivideTest  extends TestCase {
	
	private Divide divide = null;
	 
	@Override
	protected void setUp() throws Exception {
		divide = new Divide();
	}

	/**满足条件
	 * 1)必须是public
	 * 2)必须是void
	 * 3)必须以test开头
	 * 4)必须无参数
	 */
	public void testDivide(){
		int result = 0;
		try {
			result = divide.divide(10, 2);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Assert.assertEquals(5, result);
	}
	
	public void testDivide0(){
		
		Throwable tx = null;
		try {
			int result = divide.divide(10, 0);
			Assert.fail();//"出错了"的意思
		} catch (Exception e) {
			tx = e;
		}
		
		Assert.assertNotNull(tx);
		Assert.assertEquals(Exception.class, tx.getClass());
		Assert.assertEquals("除数不能为0", tx.getMessage());
		
	}
}


Java代码 复制代码
  1. package org.test;   
  2.   
  3. import junit.framework.Test;   
  4. import junit.framework.TestCase;   
  5. import junit.framework.TestSuite;   
  6.   
  7. public class TestAll extends TestCase {   
  8.        
  9.     /**  
  10.      * 方法必须这样写  
  11.      * @return  
  12.      */  
  13.     public static  Test suite(){   
  14.         TestSuite suite = new TestSuite();   
  15.            
  16.         suite.addTestSuite(DivideTest.class);   
  17.         suite.addTestSuite(AddTest.class);   
  18.            
  19.         return suite;   
  20.     }   
  21.   
  22. }  

你可能感兴趣的:(java,JUnit)