package com.hugui.juint4; public class T { public int add(int x, int y){ return x + y; } public int divide(int x, int y){ return x/y; } }
//Errors表示程序出错,Failures表示结果测试出错 //运行多个测试 package com.hugui.juint4.test; //静态引入(可以把那个类里面的静态方法引入进来),以前是import org.junit.* 但1.5之后用下面这种新的语法 import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.hamcrest.Matchers.*; import com.hugui.juint4.T; public class TTest { /* * 1. @Test: 测试方法 a) (expected=XXException.class) b) (timeout=xxx) 2. @Ignore: 被忽略的测试方法 3. @Before: 每一个测试方法之前运行 4. @After: 每一个测试方法之后运行 5. @BeforeClass: 所有测试开始之前运行 6. @AfterClass: 所有测试结束之后运行 * */ //@BeforeClass: 所有测试开始之前运行,并且方法必须是static的 @BeforeClass public static void beforeClass(){ System.out.println("beforClass"); } //@AfterClass: 所有测试结束之后运行,并且方法必须是static的 @AfterClass public static void afterClass(){ System.out.println("afterClass"); } //@Before: 每一个测试方法之前运行 @Before public void before(){ System.out.println("before"); } //加上Test注解,表示这是,能让jUnit运行时,会帮你一块儿运行 @Test public void testAdd() { // /fail("Not yet implemented"); int z = new T().add(3, 4); //判断结果是否是正确的 assertEquals(7, z); assertTrue(z>3); //"z is too small"用来起提示作用 assertTrue("z is too small", z >3); assertThat(z, is(7)); //z要满足allOf里面的所有条件,greaterThan()表示比..大,lessThan()表示比..大 assertThat(z, allOf(greaterThan(3), lessThan(10))); //是什么值都让他通过 assertThat(z, anything()); //z是不是接近7.0,误差不超过0.3,但是没有没有编译通过 //assertThat(z, closeTo(7.0, 0.3)); /* assertThat( n, allOf( greaterThan(1), lessThan(15) ) ); assertThat( n, anyOf( greaterThan(16), lessThan(8) ) ); assertThat( n, anything() ); assertThat( str, is( "hugui" ) ); assertThat( str, not( "hugui" ) ); b) assertThat( str, containsString( "hugui" ) ); assertThat( str, endsWith("hugui" ) ); assertThat( str, startsWith( "hugui" ) ); assertThat( n, equalTo( nExpected ) ); assertThat( str, equalToIgnoringCase( "hugui" ) ); assertThat( str, equalToIgnoringWhiteSpace( "hugui" ) ); c) assertThat( d, closeTo( 3.0, 0.3 ) ); assertThat( d, greaterThan(3.0) ); assertThat( d, lessThan (10.0) ); assertThat( d, greaterThanOrEqualTo (5.0) ); assertThat( d, lessThanOrEqualTo (16.0) ); d) assertThat( map, hasEntry( "hugui", "hugui" ) ); assertThat( iterable, hasItem ( "hugui" ) ); assertThat( map, hasKey ( "hugui" ) ); assertThat( map, hasValue ( "hugui" ) ); */ } //expected表示不活什么异常,timeout表示下面代码要在多少时间内完成 @Test(expected=java.lang.ArithmeticException.class, timeout=100) public void testDivide(){ int z = new T().divide(8, 2); assertThat(z, is(4)); } //@After: 每一个测试方法之后运行 @After public void after(){ System.out.println("after"); } }