單元測試利器JUnit的實踐與總結
單元測試工具Junit是一個開源項目,昨天學習了一下這個東西,總結下心得。
1.創建相應的test類
package:測試類存放位置。
Name:測試類名字。
setUp,tearDown:測試類創建測試環境以及銷毀測試環境,這兩個方法只執行一次。
Class Under test:需要被測試的類路徑及名稱。
點擊下一步就會讓你選擇需要給哪些方法進行測試。
測試類創建完成后在類中會出現你選擇的方法的測試方法:
- 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表示在執行測試方法前執行,需執行的測試方法,在測試方法執行后執行。
可以給@test添加timeout,exception參數。
在測試方法中可以用assertEquals(arg0,arg1);
可以用TestSuite把多個測試類集中到一起,統一執行測試,例如:
- 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
編輯推薦: