添加junit3与junit4的jar包的图:
创建放单元测试专用包:
一。业务类:
package com.edu.test;
public class HelloWorld {
public String hello(){
return "world";
}
public String world(){
return "hello";
}
public String nil(){
return null;
}
public String notNil(){
return "abc";
}
public String ext(){
throw new NumberFormatException();
}
}
------------------------------------------------------
二、junit3测试类(junit3的测试方法必须以test开头,而junit4不需要;junit3必须要继承TestCase,而junit4不需要继承任何类!)
package com;
import com.edu.test.HelloWorld;
import junit.framework.TestCase;
/**
* junit3 test
* @author Administrator
*
*/
public class Junit3TestHelloWord extends TestCase{
private HelloWorld hw;
@Override
protected void setUp() throws Exception {
super.setUp();
hw=new HelloWorld();
System.out.println("测试开始");
}
public void testHello(){//业务异常测试
String str=hw.hello();
assertEquals("hello 测试失败", str, "world");
}
public void testWorld(){//业务测试
String str=hw.world();
assertEquals("world 测试失败", str, "hello");
}
public void testNil(){//为空测试
assertNull("对象不为空",hw.nil());
}
public void testNotNil(){//不为空测试
assertNotNull("对象为空", hw.notNil());
}
public void testExt(){//异常测试
try {
hw.ext();
fail("没有抛出异常");//有异常,却没有抛出,说明测试失败
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
hw=null;
System.out.println("测试结束");
}
}
========================
三、junit4测试类
package com;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.edu.test.HelloWorld;
import static org.junit.Assert.*;//静态导入包中所以内容
/**
* junit4 test
* @author Administrator
*
*/
public class Junit4TestHelloWorld {
private HelloWorld hw;
@Before
public void setUp(){//测试开始
hw=new HelloWorld();
}
@Test
public void testHello(){//业务异常测试
String str=hw.hello();
assertEquals("hello 测试失败", str, "world");
}
@Test
public void testWorld(){//业务测试
String str=hw.world();
assertEquals("world 测试失败", str, "hello");
}
@Test
public void testNil(){//为空测试
assertNull("对象不为空",hw.nil());
}
@Test
public void testNotNil(){//不为空测试
assertNotNull("对象为空", hw.notNil());
}
@Test
public void junit3TestExt(){//异常测试
try {
hw.ext();
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
@Test(expected=NumberFormatException.class)//junit4独有的,junit3无法过渡
public void junit4TestExt(){//异常测试
hw.ext();
}
@After
public void tearDown(){//测试结束
hw=null;
}
}