JUnit白盒测试-第2天

来源:互联网 发布:机动车扣分查询软件 编辑:程序博客网 时间:2024/06/06 07:05
1、  在JUnit中有个assertTrue()的方法,一个是里面有String 参数的assertTrue(String msg,Boolean b),一个是没有参数的assertTrue(Boolean),那么他们两个之间到底有什么区别,其实只是一个有字符串的提示功能,也就是说假如测试出错了,那么将会在报异常的地方显示你所设置的出错信息,也就是string字符串。而如果没有这个,即使出错了,但是不知道是哪里出错了,不知道到底是什么错了,这样可能会有些麻烦。

 

package com.loulijunn.junit4.test;

import static org.junit.Assert.*;

import org.junit.Assert;

import org.junit.Test;

 

import com.loulijunn.junit4.Hello;

 

public class HelloTest {

 

    @Test

    public void testAdd() {

       //fail("Not yet implemented");

       //asset意思是断言,也就是判断到底对不对

       //Assert.assertArrayEquals(expecteds, actuals),静态引入是不需要Assert.

       int z=new Hello().add(5,3);

       assertEquals(8, z);//期望值是8,实际值是z,如果相等,就正确,否则有问题

       assertTrue(z>3);

       assertTrue("z is too small",z>10);

    }

 

}

 d

2、  在JUnit4以后,出现了一个assertThat(T actual,org.hamcrest.Matcher<T>matcher),这个assertThat()方法就替代了所有的assert方法,所以只用这一个就可以了。这里actual是实际当中的值,matcher是规则匹配器。具体的代码如下

package com.loulijunn.junit4.test;

 

import static org.junit.Assert.*;

 

import org.junit.Assert;

import org.junit.Test;

 

import com.loulijunn.junit4.Hello;

import static org.hamcrest.Matchers.*;

public class HelloTest {

 

    @Test

    public void testAdd() {

       int z=new Hello().add(5,3);

       assertThat(z , is(8));

    }

 

}

 

这里,我们好引入hamcrest的jar包,否则会报错,可以去http://code.google.com/p/hamcrest/目录下下载

 d

然后JUnit4—Build Path—Add External Archives..导入jar包,并且还要在代码中加入

import static org.hamcrest.Matchers.*;

这个静态包,而is()其实就是Matchers.*下的其中的一个方法

另外,如果这样运行的话可能会出现如下的错误,

d

这个SecurityException其实就是因为ClassLoader用的不是同一个,我们可以在www.junit.org上下载最新的JUnit4,首先把eclipse自带的那个JUnit去掉,具体就是选中那个jar包所在的目录,然后Build Path—Remove from Build Path,然后从新JUnit4—Build Path—Add External Archives..导入junit4.jar包即可

当再次运行的时候就没有问题了

3、  当然,除了is()方法,还有很多的方法,如下

a)         assertThat( n, allOf( greaterThan(1), lessThan(15) ) );
assertThat( n, anyOf( greaterThan(16), lessThan(8) ) );
assertThat( n, anything() );
assertThat( str, is( "hello" ) );
assertThat( str, not( "hello" ) );

b)         assertThat( str, containsString( "hello" ) );
assertThat( str, endsWith("hello" ) ); 
assertThat( str, startsWith( "hello" ) ); 
assertThat( n, equalTo( nExpected ) ); 
assertThat( str, equalToIgnoringCase( "hello" ) ); 
assertThat( str, equalToIgnoringWhiteSpace( "hello" ) );

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( "hello", "hello" ) );
assertThat( iterable, hasItem ( "hello" ) );
assertThat( map, hasKey ( "hello" ) );
assertThat( map, hasValue ( "hello" ) );

0 0