單元測試利器JUnit的實踐與總結(jié)
單元測試工具Junit是一個開源項目,昨天學(xué)習(xí)了一下這個東西,總結(jié)下心得。
1.創(chuàng)建相應(yīng)的test類
package:測試類存放位置。
Name:測試類名字。
setUp,tearDown:測試類創(chuàng)建測試環(huán)境以及銷毀測試環(huán)境,這兩個方法只執(zhí)行一次。
Class Under test:需要被測試的類路徑及名稱。
點擊下一步就會讓你選擇需要給哪些方法進行測試。
測試類創(chuàng)建完成后在類中會出現(xiàn)你選擇的方法的測試方法:
- package test.com.boco.bomc.alarmrelevance.show.dao;
- import junit.framework.TestCase;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.BeforeClass;
- import org.junit.Test;
- public class ShowStrategyDaoTest extends TestCase{
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- System.out.println("OK1");
- }
- @Before
- public void setUp() throws Exception {
- }
- @After
- public void tearDown() throws Exception {
- }
- @Test
- public final void testGetDataByApplyNameOrHostIp() {
- fail("Not yet implemented"); // TODO
- }
- @Test
- public final void testGetDataByObject() {
- fail("Not yet implemented"); // TODO
- }
- @Test(timeout=1)
- public final void testGetApplyUser() {
- fail("Not yet implemented"); // TODO
- }
- @Test
- public final void testGetVoiceUser() {
- fail("Not yet implemented"); // TODO
- }
- @Test
- public final void testSearchInAera() {
- fail("Not yet implemented"); // TODO
- }
- @Test
- public final void testGetDataByPolicyId() {
- fail("Not yet implemented"); // TODO
- }
- }
其中的@before,@test,@after表示在執(zhí)行測試方法前執(zhí)行,需執(zhí)行的測試方法,在測試方法執(zhí)行后執(zhí)行。
可以給@test添加timeout,exception參數(shù)。
在測試方法中可以用assertEquals(arg0,arg1);
可以用TestSuite把多個測試類集中到一起,統(tǒng)一執(zhí)行測試,例如:
- package test.com.boco.bomc.alarmrelevance.show.dao;
- import junit.framework.Test;
- import junit.framework.TestSuite;
- public class TestAll {
- public static Test suite(){
- TestSuite suite = new TestSuite("Running all the tests");
- suite.addTestSuite(ShowStrategyDaoTest.class);
- suite.addTestSuite(com.boco.bomc.alarmrelevance.show.dao.ShowStrategyDaoTest.class);
- return suite;
- }
- }
另外還可以把多個TestSuite組合到一個Test類里面,例如:
- package test.com.boco.bomc.alarmrelevance.show.dao;
- import junit.framework.Test;
- import junit.framework.TestCase;
- import junit.framework.TestSuite;
- public class TestAll1 extends TestCase {
- public static Test suite(){
- TestSuite suite1 = new TestSuite("TestAll1");
- suite1.addTest(TestAll.suite());
- suite1.addTest(TestAll2.suite());
- return suite1;
- }
- }
這就更方便與集中測試,一個方法測試完了,可以對個方法,多個類一起測試。
注意:在寫代碼的時候TestSuite,TestCase,Test的包不要到錯了。
測試效果如下:
原文鏈接:http://www.cnblogs.com/God-froest/archive/2011/11/18/JunitTest.html
編輯推薦: