Eclipse中高效的快捷鍵、調(diào)試及Junit
作者:
網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時(shí)間:
[ 2016/6/20 11:47:16 ] 推薦標(biāo)簽:
單元測(cè)試 Junit
Junit測(cè)試框架
基本使用
編寫一個(gè)新的測(cè)試類文件
在編寫的測(cè)試方法中添加注解 @Test
在大綱(Outline)視圖中右鍵點(diǎn)擊要測(cè)試的方法,運(yùn)行配置(Runas),對(duì)方法進(jìn)行運(yùn)行
如果想對(duì)類中所有的方法進(jìn)行測(cè)試,可以點(diǎn)擊類進(jìn)行測(cè)試
比如,要對(duì)一個(gè)類進(jìn)行測(cè)試
publicclassPerson{
publicvoidrun()
{
System.out.println("run!!");
}
publicvoideat()
{
System.out.println("eat!!");
}
}
其中測(cè)試類如下
importorg.junit.Test;
//Person的測(cè)試類
publicclassPersonTest{
@Test
publicvoidtestRun(){
Personp=newPerson();
p.run();
}
@Test
publicvoidtestEat(){
Personp=newPerson();
p.eat();
}
}
測(cè)試類的特殊的方法
@Before、@After
importorg.junit.After;
importorg.junit.Before;
importorg.junit.Test;
//Person的測(cè)試類
publicclassPersonTest{
privatePersonp;
@Before
publicvoidbefore()
{
System.out.println("before");
p=newPerson();
}
@Test
publicvoidtestRun(){
p.run();
}
@Test
publicvoidtestEat(){
p.eat();
}
@After
publicvoidafter()
{
System.out.println("after");
}
}
這里添加了@Before、@After兩個(gè)特殊的方法,這兩種方法在每種方法運(yùn)行的時(shí)候都會(huì)先后運(yùn)行,其用途是,把初始化資源的操作寫到@Before中,把釋放資源的操作寫到@After中。
其打印結(jié)果是
before
eat!!
after
before
run!!
after
@BeforeClass、@AfterClass
在兩種方法是在類加載和類釋放的時(shí)候進(jìn)行設(shè)計(jì)。
注意,這里的標(biāo)注的方法必須是靜態(tài)的方法。
斷言Assert
Assert.assertEquals("2",p.run());
如果這個(gè)方法不符合期望的話,那么測(cè)試不通過(guò)。