`
TechBirds
  • 浏览: 82101 次
文章分类
社区版块
存档分类
最新评论

Junit3和Junit4使用区别

 
阅读更多

在项目经常会用到单元测试,这里对Junit在开发中的使用标准及使用方法进行简单的介绍。

1.包目录的定义以及相关jar包的添加

2.Junit3和Junit4分别对测试类的编写

所测试的源代码:

package com.techbirds;
 
 public class HelloWorld {
 	
 	public void sayHello(){
 		System.out.println("hello....");
 		throw new NumberFormatException();
 	}
 	
 	public void sayWorld(){
 		System.out.println("world....");
 	}
 	
 	public String say(){
 		return "hello world!";
 	}
 	
 }
 
Junit3测试类编写:

package com.techbirds;
 
 import junit.framework.TestCase;
 
 public class HelloWorldTest extends TestCase{
 	private HelloWorld hw;
 	
 	@Override
 	protected void setUp() throws Exception {
 		super.setUp();
 		hw=new HelloWorld();
 	}
 	
 	//1.测试没有返回值
 	public void testHello(){
 		try {
 			hw.sayHello();
 		} catch (Exception e) {
 			System.out.println("发生异常.....");
 		}
 		
 	}
 	public void testWorld(){
 		hw.sayWorld();
 	}
 	//2.测试有返回值的方法
 	// 返回字符串
 	public void testSay(){
 		assertEquals("测试失败", hw.say(), "hello world!");
 	}
 	//返回对象
 	public void testObj(){
 		assertNull("测试对象不为空", null);
 		assertNotNull("测试对象为空",new String());
 	}
 	@Override
 	protected void tearDown() throws Exception {
 		super.tearDown();
 		hw=null;
 	}	
 }
 
Junit4测试类编写:

package com.techbirds;
 
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
 //导入Assert类的静态方法-为了便于junit4->junit3的转换
 import static org.junit.Assert.*;
 
 public class HelloWorldTest {
 	private HelloWorld hw;
 
 	@Before
 	public void setUp() {
 		hw = new HelloWorld();
 	}
 
 	@Test(expected=NumberFormatException.class)
 	// 1.测试没有返回值,有别于junit3的使用,更加方便
 	public void testHello() {
 		hw.sayHello();
 	}
 	@Test
 	public void testWorld() {
 		hw.sayWorld();
 	}
 	
 	@Test
 	// 2.测试有返回值的方法
 	// 返回字符串
 	public void testSay() {
 		assertEquals("测试失败", hw.say(), "hello world!");
 	}
 	
 	@Test
 	// 返回对象
 	public void testObj() {
 		assertNull("测试对象不为空", null);
 		assertNotNull("测试对象为空", new String());
 	}
 
 	@After
 	public void tearDown() throws Exception {
 		hw = null;
 	}
 
 }
 
全部测试类运行:




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics