背景
使用過 ssh 開發的人都知道,測試是個非常耗時的過程,但無法避免這個過程。一個偶然的突發奇想,我想是否可以做 main 方法一個的去測試一個 DAO 類?
帶着這個出發點,我想到了jUnit。由于SSH的東西整合了Spring,是以大量的事情是注入的,是以,如何讓jUnit加載Spring的配置檔案來執行Spring的操作,這個非常關鍵;
- 解決方案
帶着思路查找jUnit4的相關API得知,其似乎沒有這個功能,非常遺憾及失落。但并沒有立即放棄,于是檢視了Spring的API DOC,發現他另外提供了jUnit jar包。于是心中便有了一絲希望了;
接着查DOC,果然。Spring提供的jUnit jar包是支援這麼幹的。以下是具體使用方法:
- 添加Spring中jUnit4的Jar包,這是必須的
- 添加jUnit4相關的Jar包,這也是必須的。因為它提供的Jar包和原生的jUnt Jar是有依賴關系的。
- 以下是貼出來的某個類的代碼,具體測試的過程是jUnit4相關的規則,不知道的情況請去了解;
1 package com.rfsd.test.management;
2
3 import java.util.Date;
4
5 import org.junit.Before;
6 import org.junit.runner.RunWith;
7 import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.test.context.ContextConfiguration;
9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
10
11 import com.rfsd.management.entity.Area;
12 import com.rfsd.management.entity.Department;
13 import com.rfsd.management.service.DepartmentService;
14 import com.rfsd.management.service.impl.DepartmentException;
15
16 /**
17 * Department Service jUnit Test
18 *
19 * @author tony
20 * 2012-09-22
21 */
22 @RunWith(SpringJUnit4ClassRunner.class)
23 @ContextConfiguration(locations = { "classpath:applicationContext_mgt.xml" })
24 public class DepartmentServiceTest {
25
26 @Autowired
27 private DepartmentService departmentService;
28
29 private Area area;
30 private Department dep;
31
32 @Before
33 public void init() throws Exception {
34 area = new Area();
35 dep = new Department();
36
37 area.setAreaId(1);
38
39 dep.setDepartmentId(1);
40 dep.setDepartmentName("研發部");
41 dep.setDepartmentDesc("研發中心");
42 dep.setArea(area);
43 dep.setStatus((short) 1);
44 dep.setEnable(true);
45 dep.setCreatedBy("xiaosi");
46 dep.setCreationDate(new Date());
47 dep.setLastupdateBy("xiaosi");
48 dep.setLastupdateDate(new Date());
49 }
50
51 // @Test
52 public void add() throws DepartmentException {
53 departmentService.add(dep);
54 }
55
56 // @Test
57 public void altert() {
58 departmentService.alter(dep);
59 }
60
61 // @Test
62 public void remove() {
63 departmentService.remove(dep.getDepartmentId());
64 }
65
66 // @Test
67 public void findById() {
68 System.out.println(departmentService.findById(dep.getDepartmentId())
69 .getDepartmentName());
70 }
71
72 // @Test
73 public void alertStatus() {
74 departmentService.alertStatus(dep.getDepartmentId());
75 }
76
77 // @Test
78 public void findAll() {
79 System.out.println(departmentService.findAll().size());
80 }
81 }
By tony-小四 2012-09-22 22:50