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)

大家都在看

  • 商城秒杀系统总结(Java)

    本文写的较为零散,对没有基础的同学不太友好。 一、秒杀系统项目总结(基础版) classpath 在.properties中时常需要读取资源,定位文件地址时经常用到 classpa…

    Java 2023年6月7日
    095
  • Java基础 while 简单示例

    JDK :OpenJDK-11 OS :CentOS 7.6.1810 IDE :Eclipse 2019‑03 typesetting :Markdown code packag…

    Java 2023年5月29日
    093
  • 题目: 给定一个数组,添加元素(优化)

    package com.gao.test; import java.util.Scanner; /* 题目: 给定一个数组,在数组下标为2的位置上添加一个元素 */ public …

    Java 2023年6月5日
    060
  • JavaMail 网易邮件发送demo-发送带附件的邮件

    使用Java应用程序发送 E-mail,需要在机子上安装 JavaMail API 和Java Activation Framework (JAF) 。 可以从 Java 网站下载…

    Java 2023年5月29日
    079
  • Git命令备忘录

    前言 基本内容 开始之前 基础内容 基础概念 基础命令 远程仓库 分支管理 基本命令 stash命令 rebase命令 冲突问题 标签管理 前言 Git在平时的开发中经常使用,整理…

    Java 2023年6月10日
    059
  • nginx重新整理——————nginx 的网络模型[九]

    前言 简单介绍一下nginx的网络模型。 正文 网络拓扑图: 数据流: 网络传输大概是这样传输的。 nginx 事件循环: 事件处理过程: 上面两张图什么意思呢? 其实就是说,ng…

    Java 2023年5月30日
    061
  • 【Java面试手册-基础篇】Java中的main()方法能否被重载?

    答案是肯定的,我们可以重载main()方法,一个Java类可以有任意数量的main()方法,比如下面的 MainDemo 类,就有多个 main() 方法。 package com…

    Java 2023年6月8日
    082
  • java–面向对象基础

    类的定义 面向过程 :是一种以过程为中心的编程思想,实现功能的每一步,都是自己实现的面向对象 :是一种以对象为中心的编程思想,通过指挥对象实现具体的功能 类的理解 类是对现实生活中…

    Java 2023年6月15日
    075
  • 项目版本管理Git使用详细教程

    前言 记得刚开始做项目开发的时候都是一个人完成一个项目,单打独斗的开发,也不知道什么是团队开发,没有这个概念,随着工作后来知道公司里项目都是团队开发,这个时候这么多人怎么开发一个项…

    Java 2023年6月13日
    087
  • 阿里云云效流水线自动部署配置

    最近使用阿里云的云效流水线进行应用自动部署,在这里做下记录。 首先进入到阿里云云效流水线页面,入下图显示。 点击右上角的新建流水线,选择流水线模板。我的项目是java,服务器是阿里…

    Java 2023年6月16日
    0100
  • SpringBoot整合MybatisPlus基本的增删改查,保姆级教程

    概述 MybatisPlus是国产的第三方插件, 它封装了许多常用的CURDapi,免去了我们写mapper.xml的重复劳动,这里介绍了基本的整合SpringBoot和基础用法。…

    Java 2023年6月8日
    061
  • Java中@Qualifier注解

    当使用@Autowired注解按照组件类型进行注入时,若存在多个相同类型的组件时,spring就不知道该注入哪个了。此时就可以在多个相同类型的组件上使用@Component(&#8…

    Java 2023年5月29日
    077
  • 谈谈设计对软件工程目标实现的影响

    本文从个人经验出发,谈谈设计对软件工程目标实现的影响。 一、软件工程概念 首先明确下”软件工程的概念”。 看下原文(注意,原文也有一些问题,但总体没有大毛病…

    Java 2023年6月9日
    099
  • [spring]spring详细总结

    spring 1.spring简介 Spring框架是一个开源的应用程序框架,是针对bean的生命周期进行管理的轻量级容器。 Spring解决了开发者在J2EE开发中遇到的许多常见…

    Java 2023年6月6日
    086
  • 千万不要在方法上打断点!有坑!

    你好呀,我是歪歪。 我上周遇到了一个莫名其妙的搞心态的问题,浪费了我好几个小时。 气死我了,拿这几个小时来敲(摸)代(摸)码(鱼)不香吗? 主要是最后问题的解决方式也让我特别的无语…

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