spring 测试类test测试方法

实例掩码地址为:孔浩组织结构设计

spring 测试类test测试方法

web.xml配置文件:

1
2
3         contextConfigLocation
4         classpath*:beans.xml
5

测试类

1 package org.konghao.service;
 2
 3 import javax.inject.Inject;
 4
 5 import org.hibernate.Session;
 6 import org.hibernate.SessionFactory;
 7 import org.junit.After;
 8 import org.junit.Before;
 9 import org.junit.Test;
10 import org.junit.runner.RunWith;
11 import org.konghao.sys.org.iservice.IInitService;
12 import org.springframework.orm.hibernate4.SessionHolder;
13 import org.springframework.test.context.ContextConfiguration;
14 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
15 import org.springframework.transaction.support.TransactionSynchronizationManager;
16
17 @RunWith(SpringJUnit4ClassRunner.class)
18 @ContextConfiguration("/beans.xml")
19 public class TestInitService {
20     @Inject
21     private IInitService initService;
22     @Inject
23     private SessionFactory sessionFactory;
24
25     @Before
26     public void setUp() {
27         //此时最好不要使用Spring的Transactional来管理,因为dbunit是通过jdbc来处理connection,再使用spring在一些编辑操作中会造成事务shisu
28         Session s = sessionFactory.openSession();
29         TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s));
30         //SystemContext.setRealPath("D:\\teach_source\\class2\\j2EE\\dingan\\cms-da\\src\\main\\webapp");
31     }
32
33     @After
34     public void tearDown() {
35         SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
36         Session s = holder.getSession();
37         s.flush();
38         TransactionSynchronizationManager.unbindResource(sessionFactory);
39     }
40     @Test
41     public void testInitByXml() {
42         initService.initEntityByXml("orgs.xml");
43     }
44 }

解析xml文件 将信息保存到数据库;

1 package org.konghao.sys.org.service.impl;
 2
 3 import java.lang.reflect.InvocationTargetException;
 4 import java.lang.reflect.Method;
 5 import java.util.List;
 6
 7 import javax.inject.Inject;
 8
 9 import org.apache.commons.beanutils.BeanUtils;
10 import org.dom4j.Attribute;
11 import org.dom4j.Document;
12 import org.dom4j.DocumentException;
13 import org.dom4j.Element;
14 import org.dom4j.io.SAXReader;
15 import org.konghao.sys.org.iservice.IInitService;
16 import org.konghao.sys.org.model.SysException;
17 import org.springframework.beans.factory.BeanFactory;
18 import org.springframework.stereotype.Service;
19
20 @Service("initService")
21 public class InitService extends AbstractBaseSevice implements IInitService{
22
23     private Document document;
24     @Inject
25     private BeanFactory factory;
26
27     @Override
28     public void initEntityByXml(String filename) {
29         Element root = this.readDocument(filename);
30         String pname = root.attributeValue("package");
31         List initEntitys = root.selectNodes("/entitys/initEntity");
32         for (Element element : initEntitys) {
33             //如果这个实体存在就不添加
34             if (element.attributeValue("exist") == "1") {
35                 continue;
36             }else{
37                 String cname = element.attributeValue("class");
38                 cname = pname + "." + cname;
39                 String method = element.attributeValue("method");
40                 List entitys = (List)element.selectNodes("entity");
41                 addElements(cname,method,entitys);
42             }
43         }
44     }
45
46     private Element readDocument(String filename){
47         try {
48             SAXReader saxReader = new SAXReader();
49             Document d = saxReader.read( InitService.class.getClassLoader().getResourceAsStream("init/" + filename));
50             return d.getRootElement();
51         } catch (DocumentException e) {
52             e.printStackTrace();
53         }
54         return null;
55
56     }
57
58     private void addElements(String cname, String method, List entitys) {
59         for (Element element : entitys) {
60             addElement(cname , method , element);
61         }
62     }
63
64     private void addElement(String cname, String method, Element element) {
65         List attrs = element.attributes();
66         try {
67             Object o = Class.forName(cname).newInstance();
68             String[] methods = method.split("\\.");
69             if (methods.length !=2) {
70                 throw new SysException("方法格式不正确");
71             }
72             String sname = methods[0]; //对应org.xml文件的method的第一个
73             String mname = methods[1];
74             for (Attribute attribute : attrs) {
75                 System.out.println(attribute.getName() + " ; " + attribute.getValue());
76                 String name = attribute.getName();
77                 String value = attribute.getValue();
78                 BeanUtils.copyProperty(o, name, value);//利用反射进行拷贝
79             }
80             Object service = factory.getBean(sname);//该sname应该与注入的service名称一致 ,例如本地中使用的是OrgtypeService,则对应的service也是OrgTypeService,否则将报找不到该注入的类型
81             Method m = service.getClass().getMethod(mname , o.getClass());
82             m.invoke(service, o);
83         } catch (ClassNotFoundException e) {
84             e.printStackTrace();
85         } catch (IllegalAccessException e) {
86             e.printStackTrace();
87         } catch (InvocationTargetException e) {
88             e.printStackTrace();
89         } catch (SecurityException e) {
90             e.printStackTrace();
91         } catch (NoSuchMethodException e) {
92             e.printStackTrace();
93         } catch (InstantiationException e) {
94             e.printStackTrace();
95         }
96     }
97
98
99

解析文件:

1
 2 package="org.konghao.sys.org.model" >
 3     class="OrgType" method="OrgTypeService.add">
 4
 5
 6
 7
 8
 9
10
11
12
13     class="Position" method="PositionService.add">
14
15
16
17
18
19
20
21
22

底层实现:

1 package org.konghao.sys.org.service.impl;
 2
 3 import java.util.List;
 4
 5 import javax.inject.Inject;
 6
 7 import org.konghao.sys.org.idao.IOrgTypeDao;
 8 import org.konghao.sys.org.iservice.IOrgTypeService;
 9 import org.konghao.sys.org.model.OrgType;
10 import org.konghao.sys.org.model.SysException;
11 import org.springframework.stereotype.Service;
12
13 @Service("OrgTypeService")
14 public class OrgTypeService extends AbstractBaseSevice implements IOrgTypeService{
15
16     @Inject
17     private IOrgTypeDao orgTypeDao;
18
19     @Override
20     public void add(OrgType orgType) {
21         if (orgTypeDao.loadBySn(orgType.getSn()) != null) {
22             throw new SysException("要添加的组织机构类型的sn已经存在");
23         }
24         orgTypeDao.add(orgType);
25     }
26
27
28 }

spring的beans.xml配置

1
  2   3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  4     xmlns:context="http://www.springframework.org/schema/context"
  5     xmlns:tx="http://www.springframework.org/schema/tx"
  6     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8          http://www.springframework.org/schema/context
  9          http://www.springframework.org/schema/context/spring-context-3.0.xsd
 10          http://www.springframework.org/schema/aop
 11          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
 12          http://www.springframework.org/schema/tx
 13          http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
 14
 15
 16
 17     package="org.konghao" />
 18
 19     class="java.lang.String">
 20
 21
 22
 23     class="java.lang.String">
 24
 25
 26
 27     class="org.apache.commons.dbcp.BasicDataSource"
 28         destroy-method="close">
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 50      51         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
 52
 53
 54
 55
 56             org.konghao.sys.org.model
 57
 58
 59
 60
 61                 org.hibernate.dialect.MySQLDialect
 62                 true
 63                 update
 64                 true
 65
 66
 67
 68
 69
 70
 71      72         class="org.springframework.orm.hibernate4.HibernateTransactionManager">
 73
 74
 75
 76
 77
 78
 80          81             expression="execution(* org.konghao.sys.org.service.impl.*.*(..))" />
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100

————————————————————————————————————————————————————————————————————————

版本3: 多层次解析xml文件的实现

1 package org.konghao.sys.org.service.impl;
  2
  3 import java.lang.reflect.InvocationTargetException;
  4 import java.lang.reflect.Method;
  5 import java.util.Iterator;
  6 import java.util.List;
  7
  8 import javax.inject.Inject;
  9 import javax.persistence.criteria.CriteriaBuilder.In;
 10
 11 import org.apache.commons.beanutils.BeanUtils;
 12 import org.dom4j.Attribute;
 13 import org.dom4j.Document;
 14 import org.dom4j.DocumentException;
 15 import org.dom4j.Element;
 16 import org.dom4j.io.SAXReader;
 17 import org.konghao.sys.org.iservice.IInitService;
 18 import org.konghao.sys.org.model.OrgType;
 19 import org.konghao.sys.org.model.SysException;
 20 import org.springframework.beans.factory.BeanFactory;
 21 import org.springframework.stereotype.Service;
 22
 23 @Service("initService")
 24 public class InitService extends AbstractBaseSevice implements IInitService{
 25
 26     private Document document;
 27     @Inject
 28     private BeanFactory factory;
 29
 30     @Override
 31     public void initEntityByXml(String filename) {
 32         Element root = this.readDocument(filename);
 33         String pname = root.attributeValue("package");
 34         List initEntitys = root.selectNodes("/entitys/initEntity");
 35         for (Element element : initEntitys) {
 36             String ipname = element.attributeValue("package");
 37             String cname = element.attributeValue("class");
 38             System.out.println(element.attributeValue("exist"));
 39             //如果为1 表示已经添加过了
 40             if (element.attributeValue("exist") == "1" || element.attributeValue("exist").equals("1")) {
 41                 continue;
 42             }if (ipname != null && !"".equals(ipname)) {
 43                 cname = ipname + "." + cname;
 44             } else{
 45                 cname = pname + "." + cname;
 46             }
 47             String method = element.attributeValue("method");
 48             List entitys = (List)element.selectNodes("entity");
 49             System.out.println(cname + "  " + method );
 50             addElements(cname,method,entitys);
 51
 52         }
 53     }
 54
 55     private Element readDocument(String filename){
 56         try {
 57             SAXReader saxReader = new SAXReader();
 58             Document d = saxReader.read( InitService.class.getClassLoader().getResourceAsStream("init/" + filename));
 59             return d.getRootElement();
 60         } catch (DocumentException e) {
 61             e.printStackTrace();
 62         }
 63         return null;
 64
 65     }
 66
 67     private void addElements(String cname, String method, List entitys) {
 68         for (Element element : entitys) {
 69             addElement(cname , method , element , null);
 70         }
 71     }
 72
 73     private void addElement(String cname, String method, Element e,Object parent) {
 74         try {
 75             //获取所有的属性
 76             List atts = (List)e.attributes();
 77             Object obj = Class.forName(cname).newInstance();
 78             String [] ms = method.split("\\.");
 79             if(ms.length!=2) throw new SysException("方法格式不正确");
 80             String sname = ms[0]; String mname = ms[1];
 81             for(Attribute att:atts) {
 82                 String name = att.getName();
 83                 String value = att.getValue();
 84                 BeanUtils.copyProperty(obj, name, value);
 85             }
 86             if(parent!=null) {
 87                 BeanUtils.copyProperty(obj, "parent", parent);
 88             }
 89             Object service = factory.getBean(sname);
 90             Method m = service.getClass().getMethod(mname,obj.getClass());
 91             m.invoke(service, obj);
 92             List es = e.selectNodes("entity");
 93             for(Element ele:es) {
 94                 addElement(cname, method, ele, obj);
 95             }
 96         } catch (ClassNotFoundException e1) {
 97             e1.printStackTrace();
 98         } catch (IllegalAccessException e1) {
 99             e1.printStackTrace();
100         } catch (InvocationTargetException e1) {
101             e1.printStackTrace();
102         } catch (SecurityException e1) {
103             e1.printStackTrace();
104         } catch (NoSuchMethodException e1) {
105             e1.printStackTrace();
106         } catch (InstantiationException e1) {
107             e1.printStackTrace();
108         }
109     }
110
111 }

实体类Org

1 package org.konghao.sys.org.model;
  2
  3 import java.util.List;
  4
  5 import javax.persistence.Column;
  6 import javax.persistence.Entity;
  7 import javax.persistence.GeneratedValue;
  8 import javax.persistence.Id;
  9 import javax.persistence.JoinColumn;
 10 import javax.persistence.ManyToOne;
 11 import javax.persistence.Table;
 12
 13 /**
 14  * 组织对象,该表可以生成完整的组织树
 15  * 根据组织类型来具体存储实际中存在的组织
 16  * 学院  --> xx
 17  * 校本部--> FX
 18  * 南校区--> FX
 19  * @author jrx
 20  *
 21  */
 22 @Entity
 23 @Table(name="t_org")
 24 public class Org {
 25
 26     /**
 27      *  组织机构的id
 28      */
 29     private int id;
 30     /**
 31      * 组织机构的名称
 32      */
 33     private String name ;
 34     /**
 35      * 组织机构所属类型的id,此处不要使用ManyToOne
 36      */
 37     private Integer typeId;
 38     /**
 39      * 组织机构所属类型的名称,冗余
 40      */
 41     private String typeName;
 42     /**
 43      * 组织机构的排序号
 44      */
 45     private Integer orderNum ;
 46     /**
 47      * 组织机构的父亲组织
 48      */
 49     private Org parent ;
 50     /**
 51      * 管理类型
 52      */
 53     private int managerType;
 54     /**
 55      * 组织机构的地址
 56      */
 57     private String address ;
 58     /**
 59      * 组织机构的电话
 60      */
 61     private String phone ;
 62     /**
 63      * 扩展属性,用于在针对某些特殊的组织存储相应的信息
 64      */
 65     private String att1 ;
 66     private String att2 ;
 67     private String att3 ;
 68
 69     @Id
 70     @GeneratedValue
 71     public int getId() {
 72         return id;
 73     }
 74
 75     public void setId(int id) {
 76         this.id = id;
 77     }
 78
 79     public String getName() {
 80         return name;
 81     }
 82
 83     public void setName(String name) {
 84         this.name = name;
 85     }
 86
 87     @Column(name="tid")
 88     public Integer getTypeId() {
 89         return typeId;
 90     }
 91
 92     public void setTypeId(Integer typeId) {
 93         this.typeId = typeId;
 94     }
 95     @Column(name="tname")
 96     public String getTypeName() {
 97         return typeName;
 98     }
 99
100     public void setTypeName(String typeName) {
101         this.typeName = typeName;
102     }
103     @Column(name="order_num")
104     public Integer getOrderNum() {
105         return orderNum;
106     }
107
108     public void setOrderNum(Integer orderNum) {
109         this.orderNum = orderNum;
110     }
111     @ManyToOne
112     @JoinColumn(name="pid")
113     public Org getParent() {
114         return parent;
115     }
116
117     public void setParent(Org parent) {
118         this.parent = parent;
119     }
120
121     public String getAddress() {
122         return address;
123     }
124
125     public void setAddress(String address) {
126         this.address = address;
127     }
128
129     public String getPhone() {
130         return phone;
131     }
132
133     public void setPhone(String phone) {
134         this.phone = phone;
135     }
136
137     public String getAtt1() {
138         return att1;
139     }
140
141     public void setAtt1(String att1) {
142         this.att1 = att1;
143     }
144
145     public String getAtt2() {
146         return att2;
147     }
148
149     public void setAtt2(String att2) {
150         this.att2 = att2;
151     }
152
153     public String getAtt3() {
154         return att3;
155     }
156
157     public void setAtt3(String att3) {
158         this.att3 = att3;
159     }
160
161     @Column(name = "manager_type")
162     public int getManagerType() {
163         return managerType;
164     }
165
166     public void setManagerType(int managerType) {
167         this.managerType = managerType;
168     }
169
170     @Override
171     public String toString() {
172         return "Org [id=" + id + ", name=" + name + ", typeId=" + typeId
173                 + ", typeName=" + typeName + ", orderNum=" + orderNum
174                 + ", parent=" + parent + ", managerType=" + managerType
175                 + ", address=" + address + ", phone=" + phone + ", att1="
176                 + att1 + ", att2=" + att2 + ", att3=" + att3 + "]";
177     }
178
179
180 }

底层实现:

 1 package org.konghao.sys.org.service.impl;
 2
 3 import java.util.List;
 4
 5 import javax.inject.Inject;
 6
 7 import org.konghao.basic.model.Pager;
 8 import org.konghao.sys.dto.TreeDto;
 9 import org.konghao.sys.org.idao.IOrgDao;
10 import org.konghao.sys.org.idao.IOrgTypeDao;
11 import org.konghao.sys.org.iservice.IOrgService;
12 import org.konghao.sys.org.model.Org;
13 import org.konghao.sys.org.model.SysException;
14 import org.springframework.stereotype.Service;
15
16 @Service("orgService")
17 public class OrgService extends AbstractBaseSevice implements IOrgService {
18
19
20     @Inject
21     private IOrgDao orgDao;
22
23     @Inject
24     private IOrgTypeDao orgTypeDao;
25
26     private void checkChildOrgNum(Org cOrg , Org pOrg){
27         if (pOrg == null) {
28             return;
29         }
30         //获取根据组织类型获取某组织类型下组织的数量(数量根据OrgTypeRule的num来确定数量,即某类型下组织数量需小于等于OrgTypeRule中num的数量)
31         int hnum = orgDao.loadNumByType(pOrg.getId(), cOrg.getTypeId());
32         //根据组织类型的父id和子id获取num数量
33         int rnum = orgTypeDao.loadOrgTypeRuleNum(pOrg.getTypeId(), cOrg.getTypeId());
34         if (rnum < 0) {
35             return;
36         }
37         if (hnum >= rnum) {
38             throw new SysException(pOrg.getName() +"下的" + cOrg.getName() + "的数量已经达到最大化");
39         }
40     }
41
42     //parent已经存在的添加
43     @Override
44     public void add(Org org) {
45         checkChildOrgNum(org, org.getParent());
46         if (org.getParent() != null) {
47             org.setOrderNum(orgDao.getMaxOrder(org.getParent().getId()));
48         }else {
49             org.setOrderNum(null);
50         }
51         orgDao.add(org);
52     }
53
54     @Override
55     public void add(Org org, Integer pid) {
56         if (pid != null) {
57             Org p = orgDao.load(pid);
58             if (p == null) {
59                 throw new SysException("要添加的父组织不存在");
60             }
61             checkChildOrgNum(org, org.getParent());
62             org.setParent(p);
63         }
64         org.setOrderNum(orgDao.getMaxOrder(pid));
65         orgDao.add(org);
66     }
67
68 }

Original: https://www.cnblogs.com/a757956132/p/6072962.html
Author: a757956132
Title: spring 测试类test测试方法

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/540797/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • Nginx核心知识100讲学习笔记(陶辉)详解HTTP模块(详解11阶段)

    一、server_name指令 1、指令后可跟多个域名。第一个是主域名 bash;gutter:true; Syntax server_name_in_redirect on | …

    Java 2023年5月30日
    077
  • spring 拦截器流程 HandlerInterceptor AsyncHandlerInterceptor HandlerInterceptorAdapter

    HandlerInterceptor源码 3种方法: preHandle:拦截于请求刚进入时,进行判断,需要boolean返回值,如果返回true将继续执行,如果返回false,将…

    Java 2023年6月5日
    0135
  • IDEA05 mybatis插件之MyBatisCodeHelper-Pro

    前提准备: 》IDEA专业版本 1 安装MyBatisCodeHelper-Pro IDEA提供了插件安装功能,可以根据开发需要安装适合的插件 》help -> find a…

    Java 2023年5月30日
    0168
  • leetcode 83. Remove Duplicates from Sorted List 删除排序链表中的重复元素(简单)

    一、题目大意 给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。 示例 1: 输入:head = [1,1,2]输出:[1,…

    Java 2023年6月14日
    0123
  • SpringBoot中配置Logback日志输出

    因为在SpringBoot中默认使用的Logback日志系统,所以SpringBoot已经集成了相关依赖,无需多余的依赖,只需在src/main/resources文件夹下,增加l…

    Java 2023年5月30日
    071
  • EMQX 入门实战(1)–安装及简单使用

    EMQX 是基于 Erlang/OTP 平台开发的开源物联网 MQTT 消息服务器,本文主要介绍其安装及简单使用,文中使用到的软件版本:emqx 4.4.2、Centos 7. 1…

    Java 2023年6月16日
    075
  • 一份简明的 Base64 原理解析

    书接上回,在 记一个 Base64 有关的 Bug 一文里,我们说到了 Base64 的编解码器有不同实现,交叉使用它们可能引发的问题等等。 这一回,我们来对 Base64 这一常…

    Java 2023年6月5日
    079
  • commons-collections1链分析

    概述 Commons Collections增强了Java集合框架。 它提供了几个功能来简化收集处理。 它提供了许多新的接口,实现和实用程序。在反序列化里,cc1这里主要就是Tra…

    Java 2023年6月6日
    089
  • Java实现pdf转html

    引入pdf2dom net.sf.cssbox pdf2dom 1.8 测试代码: import java.io.File; import java.io.FileInputStr…

    Java 2023年5月29日
    070
  • 【转】MongoDB 3.0 正式版本即将发布,强力推荐

    MongoDB 今天宣布3.0 正式版本即将发布。这标志着 MongoDB 数据库进入了一个全新的发展阶段,提供强大、灵活而且易于管理的数据库管理系统。 MongoDB 3.0 在…

    Java 2023年6月6日
    074
  • map和flatMap的区别

    转自: Optional 类简介: Java8 新增了非常多的特性,而Optional 类就是其中一个新增的类 Optional 类是一个可以为null的容器对象。如果值存在则is…

    Java 2023年6月15日
    080
  • 简易线程池的实现

    1 线程池 为了避免多线程操作过程种线程频繁申请和释放所带来的性能消耗,可以提前创建多个线程,当有任务到来时从线程池中选择一个线程执行,执行完后继续在线程池中待命。 核心是使用一个…

    Java 2023年5月30日
    0109
  • JavaSE前期准备3

    修饰符 成员方法 构造方法 成员变量 局部变量 abstract(抽象的) static (静态的) public(公共的) protected(受保护的) private(私有的…

    Java 2023年6月5日
    084
  • Java-Reflection(JAVA反射)

    Java-Reflection(JAVA反射)是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够通过Java-Reflection来调用它的…

    Java 2023年5月29日
    045
  • SSM-配置

    Day3 分模块开发 建立多个applicationContext配置文件,在主配置文件中通过import标签引用其他配置文件 Spring相关api ApplicationCon…

    Java 2023年6月5日
    084
  • python协程–asyncio模块(基础并发测试)

    在高并发的场景下,python提供了一个多线程的模块threading,但似乎这个模块并不近人如意,原因在于cpython本身的全局解析锁(GIL)问题,在一段时间片内实际上的执行…

    Java 2023年6月14日
    075
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球