选用框架为Spring2.0 + Hibernate 3.2 + Struts2.0 + Junit4.7
1、首先用一个基础测试类继承Spring的AbstractTransactionalDataSourceSpringContextTests类,在getConfigLocations方法中申明配置文件的存放路径。
- package service;
-
- import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
-
- public class BaseServiceTest extends
- AbstractTransactionalDataSourceSpringContextTests {
-
- protected String[] getConfigLocations() {
- setAutowireMode(AUTOWIRE_BY_TYPE);
- return new String[] { "classpath*:cfg/spring/*.xml",
- "file:WebRoot/WEB-INF/applicationContext.xml" };
- }
-
- }
package service;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
public class BaseServiceTest extends
AbstractTransactionalDataSourceSpringContextTests {
protected String[] getConfigLocations() {
setAutowireMode(AUTOWIRE_BY_TYPE);
return new String[] { "classpath*:cfg/spring/*.xml",
"file:WebRoot/WEB-INF/applicationContext.xml" };
}
}
2、具体的Service单元测试如下:
- package service;
-
- import java.util.List;
-
- import org.junit.Test;
-
- import com.ys.system.dept.bean.SysDept;
- import com.ys.system.dept.service.IDeptService;
-
- public class DeptServiceTest extends BaseServiceTest {
-
- private final static int UNIT_ID = 79;
- private static int DEPT_ID;
-
- private IDeptService deptService;
-
- public void setDeptService(IDeptService deptService) {
- this.deptService = deptService;
- }
-
- @Test
- public void testDeptsOfList() {
- System.out.println("\n");
- List<SysDept> depts = deptService.findDeptsOfUnit(UNIT_ID);
- for (SysDept sysDept : depts) {
- System.out.println(sysDept);
- }
- }
-
- @Test
- public void testChildDepts() {
- System.out.println("\n");
- List<SysDept> depts = deptService.findChildDepts(0);
- for (SysDept sysDept : depts) {
- System.out.println(sysDept);
- }
- }
-
- @Test
- public void testSaveAndUpdate() {
- System.out.println("\n");
- SysDept dept = new SysDept();
- dept.setDeptName("service_test");
- dept.setDeptDescription("测试");
- dept.setParentDeptId(0);
- dept.setUnitId(UNIT_ID);
- deptService.save(dept);
-
-
- setComplete();
- assertNotNull(dept.getId());
- DEPT_ID = dept.getId();
-
- dept.setDeptDescription("修改部门备注");
- deptService.save(dept);
- setComplete();
- assertEquals(dept.getDeptDescription(), "修改部门备注");
- }
-
- @Test
- public void testFindByIdAndDelete() {
- System.out.println("\n");
- SysDept dept = deptService.findById(DEPT_ID);
- assertNotNull(dept.getDeptName());
- System.out.println(dept.getDeptName());
-
- deptService.delete(dept);
- setComplete();
-
- dept = deptService.findById(DEPT_ID);
- assertNull(dept);
- }
-
- }