Java中使用JUnit测试

来源:互联网 发布:数据存储管理 编辑:程序博客网 时间:2024/05/29 04:48
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 静态初始化,类加载的时候初始化一次--------");}@AfterClasspublic static void afterClass() {System.out.println("after Class 静态销毁,销毁一次--------");}@Beforepublic void before() {System.out.println("before 测试方法执行前执行 --------");}@Afterpublic void after() {System.out.println("after 测试方法执行后执行 --------");}// 对包含测试类的类或@Test注解方法使用@Ignore注解将使被注解的类或方法不会被当做测试执行@Ignore@Testpublic void testAdd() {// 1. 准备 givenArrayList<String> target = new ArrayList<String>();// 2. 执行 whentarget.add("Abc");// 3. 校验 thenassertTrue("", target.contains("Abc"));}@Testpublic 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);}}

0 0
原创粉丝点击