Java中使用JUnit测试

package ray.junit;

import static org.junit.Assert.*;

import java.util.ArrayList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

public class ArrayListTest {

	@BeforeClass
	// 此方法相当于静态初始化,类加载的时候初始化一次
	public static void beforeClass() {
		System.out.println("before Class 静态初始化,类加载的时候初始化一次--------");
	}

	@AfterClass
	public static void afterClass() {
		System.out.println("after Class 静态销毁,销毁一次--------");
	}

	@Before
	public void before() {
		System.out.println("before 测试方法执行前执行 --------");
	}

	@After
	public void after() {
		System.out.println("after 测试方法执行后执行 --------");
	}

	// 对包含测试类的类或@Test注解方法使用@Ignore注解将使被注解的类或方法不会被当做测试执行
	@Ignore
	@Test
	public void testAdd() {
		// 1. 准备 given
		ArrayList<String> target = new ArrayList<String>();
		// 2. 执行 when
		target.add("Abc");
		// 3. 校验 then
		assertTrue("", target.contains("Abc"));
	}

	@Test
	public void testMath() {
		// assertTrue("不相等",Math.abs(-1) == 12);
		assertEquals(Math.abs(-1), 1);
	}

	@Test
	// same比较的是对象的地址
	public void testSame() {
		String s1 = new String("1");
		String s2 = new String("1");
		assertSame("not same", s1, s2);
	}

	@Test
	// equals比较的是对象的内容
	public void testEquals() {
		String s1 = new String("1");
		String s2 = new String("1");
		assertEquals("not equals", s1, s2);
	}
	/*
	 * @Test注解提供2个参数:
	 * 
	 * 1,“expected”,定义测试方法应该抛出的异常,如果测试方法没有抛出异常或者抛出了一个不同的异常,测试失败
	 * 
	 * 2,“timeout”,如果测试运行时间长于该定义时间,测试失败(单位为毫秒)
	 */
	@Test(expected=Exception.class)
	public void testException() throws Exception{
		throw new Exception();
	}
	
	@Test(timeout=1000)
	public void testTimeOut() throws InterruptedException{
		Thread.sleep(2000);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值