Junit4入门

 eclipse自带junit包,可右键直接新建junit类

静态引入:import static org.junit.Assert.*

assert.*是类,静态引入会引入assert里的所有静态方法,可以不用写类名直接调用静态方法。非常多的assert方法。

运行结果:keep the bar green to keep the code clean。

----------------------

实战的时候查一下Junit的API/hamcrest api

大部分asset方法都重载了一个可以加入string参数的方法,string可以传入作为false的提示消息。

assetEquals

assetFalse

assetTrue

assetSame

assertNotNull/assertNull

assertThat

-----------------------

Junit4以后添加assertThat可以实现上面所有的assert方法。需要加入hamcrest包:hamcrest-core/hamcrest-lib。hamcrest里有Matchers方法

AssertThat(实际值,Matchers.is(表达式))

hamcrest用eclipse自带的junit会造成类加载错误,引入新的junit包即可解决。

hamcrest里Matchers有很多写好的现成可用的方法,提供很多简单可用的。如果单元测试比较简单,不用assertThat也可以。

------------------------

注解:

@Test(expected=java.lang.异常类.class)可用于专门测试抛出异常的方法

@Test(timeout=100)用于测试执行效率

@Ignore用于@Test前面

@BeforeClass/@AfterClass:必须是静态方法。测试前比较耗时间的环境或是资源实使用此方法。eg:加载spring配置文件,建立数据库连接。

@Before/@After

-------------------------

运行多个测试:

eclipse右键run configuration,可以选择跑某一个项目或事文件夹下的所有junit test,用这种方式来控制junit运行。

原文地址:https://www.cnblogs.com/vivian-test/p/5397976.html