JUnit常用实例

1.常用@标签

 

 

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class NormalTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		System.out.println("只执行一次");
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		System.out.println("只执行一次");
	}

	@Before
	public void setUp() throws Exception {
		System.out.println("每次调用test方法都执行一次");
	}

	@After
	public void tearDown() throws Exception {
		System.out.println("每次调用test方法都执行一次");
	}
	
	@Test(timeout=1000)
	public void testTimeout(){
		try {
			Thread.sleep(1200);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("NormalTest.normalTest()");
	}

	@Test(expected=Exception.class)
	public void testExpectedException() throws Exception{
		System.out.println("NormalTest.expectedExceptionTest()");
		throw new Exception();
	}
	
}
 

 

2.参数化测试

 

import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class ParametersTest {

	private String expected;
	private String target;

	@Parameters
	public static Collection words() {
		return Arrays.asList(new Object[][] { { "employee_info", "employeeInfo" }, // 测试一般的处理情况
				{ null, null }, 						// 测试 null 时的处理情况
				{ "", "" }, 							// 测试空字符串时的处理情况
				{ "employee_info", "EmployeeInfo" }, 	// 测试当首字母大写时的情况
				{ "employee_info_a", "employeeInfoA" }, // 测试当尾字母为大写时的情况
				{ "employee_a_info", "employeeAInfo" } 	// 测试多个相连字母大写时的情况
				});
	}

	/**
	 * 参数化测试必须的构造函数
	 * 
	 * @param expected
	 *            期望的测试结果,对应参数集中的第一个参数
	 * @param target
	 *            测试数据,对应参数集中的第二个参数
	 */
	public ParametersTest(String expected, String target) {
		this.expected = expected;
		this.target = target;
	}

	/**
	 * 测试将 Java 对象名称到数据库名称的转换
	 */
	@Test
	public void wordFormat4DB() {
		assertEquals(expected, target);
	}
}
 

3.测试套件TestSuite

 

 

import junit.framework.Test;
import junit.framework.TestSuite;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({ NormalTest.class })
public class AllTests {
	
	/*public static Test suite() {
		TestSuite suite = new TestSuite(AllTests.class.getName());
		// $JUnit-BEGIN$
		suite.addTestSuite(NormalTest.class);//添加测试的类 ,必须是TestCase的子类
		// $JUnit-END$
		return suite;
	}*/

}
 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值