首页 > 代码库 > ant整合junit自动化测试

ant整合junit自动化测试

一. 使用Junit进行测试

1. Java业务代码:

public class HelloWorld {
	// 测试返回"world"
	public String hello() {
		return "world";
	}
	
	// 测试返回"hello"
	public String world() {
		return "hello";
	}

	// 测试为空
	public String nil() {
		return null;
	}
	
	// 测试不为空
	public String notNil() {
		return "abc";
	}
	
	// 测试抛出异常
	public String ext() {
		return null;
	}
}

2. 使用junit3测试, 继承TestCase

import junit.framework.TestCase;
public class HelloWorldTest extends TestCase {
	private HelloWorld helloWorld; 

	@Override
	protected void setUp() throws Exception {
		helloWorld = new HelloWorld();
		System.out.println("helloWorld init");
	}

	public void testHello() {
		String str = helloWorld.hello();
		assertEquals("测试world失败", str, "world");
	}

	public void testWorld() {
		String str = helloWorld.world();
		assertEquals("测试world失败", str, "hello");
	}

	public void testNotNil() {
		assertNotNull("对象为空", helloWorld.notNil());
	}

	public void testNil() {
		assertNull("对象不为空", helloWorld.nil());
	}

	public void testExt() {
		try {
			helloWorld.ext();
			fail("没有抛出异常");
		} catch (NumberFormatException e) {
		}
	}

	@Override
	protected void tearDown() throws Exception {
		System.out.println("hello world destory");
		helloWorld = null;
	}
}

4. 使用junit4测试, 使用注解

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;   // 静态引入, assertEquals兼容junit3
public class HelloWorldTest {
	private HelloWorld helloWorld; 
	
	@Before
	public void setUp() {
		helloWorld = new HelloWorld();
	}
	
	@Test
	public void testHello() {
		String str = helloWorld.hello();
		assertEquals("hello测试失败",str,"world");
	}
	
	@Test
	public void testWorld() {
		String str = helloWorld.world();
		assertEquals("world测试失败",str, "hello");
	}
	
	@Test
	public void testNil() {
		assertNull("对象不为空",helloWorld.nil());
	}
	
	@Test
	public void testNotNil() {
		assertNotNull("对象为空", helloWorld.notNil());
	}
	
	@Test(expected=NumberFormatException.class)
	public void testExt() {
		helloWorld.ext();
	}
	
	@After
	public void tearDown() {
		helloWorld = null;
	}
}