jUnit 4 在 s2sh 中的应用

  • 背景

     使用过 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

    

原文地址:https://www.cnblogs.com/tonycody/p/2698532.html