使用TestNG的弹簧测试支持

TestNG是一个测试框架,旨在涵盖所有类别的测试:单元,功能,端到端,集成等。 它包括许多功能,例如灵活的测试配置,对数据驱动测试的支持(使用@DataProvider),强大的执行模型(不再需要TestSuite)(等等)。

弹簧测试支持涵盖了基于弹簧的应用程序的单元和集成测试的非常有用和重要的功能。 org.springframework.test.context.testng包为基于TestNG的测试用例提供支持类。 本文展示了如何通过使用Spring和TestNG集成来测试Spring Service层组件。 下一篇文章还将展示如何使用相同的集成来测试Spring Data Access层组件。

二手技术:

JDK 1.6.0_31
春天3.1.1
测试NG 6.4 Maven的3.0.2

步骤1:建立已完成的专案

如下创建一个Maven项目。 (可以使用Maven或IDE插件来创建它)。

步骤2:图书馆

Spring依赖项已添加到Maven的pom.xml中。

<properties><spring.version>3.1.1.RELEASE</spring.version></properties><dependencies><!-- Spring 3 dependencies --><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version></dependency><!-- TestNG dependency --><dependency><groupId>org.testng</groupId><artifactId>testng</artifactId><version>6.4</version></dependency><!-- Log4j dependency --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.16</version></dependency></dependencies>

步骤3:建立使用者类别

创建一个新的用户类。

package com.otv.user;/*** User Bean** @author  onlinetechvision.com* @since   19 May 2012* @version 1.0.0**/
public class User {private String id;private String name;private String surname;/*** Gets User Id** @return String id*/public String getId() {return id;}/*** Sets User Id** @param String id*/public void setId(String id) {this.id = id;}/*** Gets User Name** @return String name*/public String getName() {return name;}/*** Sets User Name** @param String name*/public void setName(String name) {this.name = name;}/*** Gets User Surname** @return String Surname*/public String getSurname() {return surname;}/*** Sets User Surname** @param String surname*/public void setSurname(String surname) {this.surname = surname;}@Overridepublic String toString() {StringBuilder strBuilder = new StringBuilder();strBuilder.append("Id : ").append(getId());strBuilder.append(", Name : ").append(getName());strBuilder.append(", Surname : ").append(getSurname());return strBuilder.toString();}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((id == null) ? 0 : id.hashCode());result = prime * result + ((name == null) ? 0 : name.hashCode());result = prime * result + ((surname == null) ? 0 : surname.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;User other = (User) obj;if (id == null) {if (other.id != null)return false;} else if (!id.equals(other.id))return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;if (surname == null) {if (other.surname != null)return false;} else if (!surname.equals(other.surname))return false;return true;}
}

步骤4:创建NonExistentUserException类

NonExistentUserException类已创建。

package com.otv.common.exceptions;/*** Non Existent User Exception** @author  onlinetechvision.com* @since   19 May 2012* @version 1.0.0**/
public class NonExistentUserException extends Exception {private static final long serialVersionUID = 1L;public NonExistentUserException(String message) {super(message);}
}

第5步:创建ICacheService接口

创建了代表缓存服务接口的ICacheService接口。

package com.otv.cache.service;import java.util.concurrent.ConcurrentHashMap;import com.otv.user.User;/*** Cache Service Interface** @author  onlinetechvision.com* @since   19 May 2012* @version 1.0.0**/
public interface ICacheService {/*** Gets User Map** @return ConcurrentHashMap User Map*/ConcurrentHashMap<String, User> getUserMap();}

步骤6:创建CacheService类

CacheService类是通过实现ICacheService接口创建的。 它提供对远程缓存的访问…

package com.otv.cache.service;import java.util.concurrent.ConcurrentHashMap;import com.otv.user.User;/*** Cache Service Implementation** @author  onlinetechvision.com* @since   19 May 2012* @version 1.0.0**/
public class CacheService implements ICacheService {//User Map is injected...private ConcurrentHashMap<String, User> userMap;/*** Gets User Map** @return ConcurrentHashMap User Map*/public ConcurrentHashMap<String, User> getUserMap() {return userMap;}/*** Sets User Map** @param ConcurrentHashMap User Map*/public void setUserMap(ConcurrentHashMap<String, User> userMap) {this.userMap = userMap;}}

步骤7:建立IUserService介面

创建了代表用户服务接口的IUserService接口。

package com.otv.user.service;import java.util.Collection;import com.otv.common.exceptions.NonExistentUserException;
import com.otv.user.User;/**** User Service Interface** @author  onlinetechvision.com* @since   19 May 2012* @version 1.0.0**/
public interface IUserService {/*** Adds User** @param  User user* @return boolean whether delete operation is success or not.*/boolean addUser(User user);/*** Deletes User** @param  User user* @return boolean whether delete operation is success or not.*/boolean deleteUser(User user);/*** Updates User** @param  User user* @throws NonExistentUserException*/void updateUser(User user) throws NonExistentUserException;/*** Gets User** @param  String User Id* @return User*/User getUserById(String id);/*** Gets User Collection** @return List - User list*/Collection<User> getUsers();
}

步骤8:创建UserService类

通过实现IUserService接口创建UserService类。

package com.otv.user.service;import java.util.Collection;
import com.otv.cache.service.ICacheService;
import com.otv.common.exceptions.NonExistentUserException;
import com.otv.user.User;/**** User Service** @author  onlinetechvision.com* @since   19 May 2012* @version 1.0.0**/
public class UserService implements IUserService {//CacheService is injected...private ICacheService cacheService;/*** Adds User** @param  User user* @return boolean whether delete operation is success or not.*/public boolean addUser(User user) {getCacheService().getUserMap().put(user.getId(), user);if(getCacheService().getUserMap().get(user.getId()).equals(user)) {return true;}return false;}/*** Deletes User** @param  User user* @return boolean whether delete operation is success or not.*/public boolean deleteUser(User user) {User removedUser = getCacheService().getUserMap().remove(user.getId());if(removedUser != null) {return true;}return false;}/*** Updates User** @param  User user* @throws NonExistentUserException*/public void updateUser(User user) throws NonExistentUserException {if(getCacheService().getUserMap().containsKey(user.getId())) {getCacheService().getUserMap().put(user.getId(), user);} else {throw new NonExistentUserException("Non Existent User can not update! User : "+user);}}/*** Gets User** @param  String User Id* @return User*/public User getUserById(String id) {return getCacheService().getUserMap().get(id);}/*** Gets User List** @return Collection - Collection of Users*/public Collection<User> getUsers() {return (Collection<User>) getCacheService().getUserMap().values();}/*** Gets Cache Service** @return ICacheService - Cache Service*/public ICacheService getCacheService() {return cacheService;}/*** Sets Cache Service** @param ICacheService - Cache Service*/public void setCacheService(ICacheService cacheService) {this.cacheService = cacheService;}}

步骤9:创建UserServiceTester类

通过扩展AbstractTestNGSpringContextTests创建用户服务测试器类。

package com.otv.user.service.test;import junit.framework.Assert;import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;import com.otv.common.exceptions.NonExistentUserException;
import com.otv.user.User;
import com.otv.user.service.IUserService;/*** User Service Tester Class** @author  onlinetechvision.com* @since   19 May 2012* @version 1.0.0**/
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class UserServiceTester extends AbstractTestNGSpringContextTests {private static Logger logger = Logger.getLogger(UserServiceTester.class);@Autowiredprivate IUserService userService;private User firstUser;private User secondUser;private User thirdUser;/*** Creates Test Users**/private void createUsers() {firstUser = new User();firstUser.setId("1");firstUser.setName("Lionel");firstUser.setSurname("Messi");secondUser = new User();secondUser.setId("2");secondUser.setName("David");secondUser.setSurname("Villa");thirdUser = new User();thirdUser.setId("3");thirdUser.setName("Andres");thirdUser.setSurname("Iniesta");}/*** Asserts that User Properties are not null.** @param User*/private void assertNotNullUserProperties(User user) {Assert.assertNotNull("User must not be null!", user);Assert.assertNotNull("Id must not be null!", user.getId());Assert.assertNotNull("Name must not be null!", user.getName());Assert.assertNotNull("Surname must not be null!", user.getSurname());}/*** The annotated method will be run before any test method belonging to the classes* inside the <test> tag is run.**/@BeforeTestpublic void beforeTest() {logger.debug("BeforeTest method is run...");}/*** The annotated method will be run before the first test method in the current class* is invoked.**/@BeforeClasspublic void beforeClass() {logger.debug("BeforeClass method is run...");createUsers();}/*** The annotated method will be run before each test method.**/@BeforeMethodpublic void beforeMethod() {logger.debug("BeforeMethod method is run...");} /*** Tests the process of adding user**/@Testpublic void addUser() {assertNotNullUserProperties(firstUser);Assert.assertTrue("User can not be added! User : " + firstUser, getUserService().addUser(firstUser));}/*** Tests the process of querying user**/@Testpublic void getUserById() {User tempUser = getUserService().getUserById(firstUser.getId());assertNotNullUserProperties(tempUser);Assert.assertEquals("Id is wrong!", "1", tempUser.getId());Assert.assertEquals("Name is wrong!", "Lionel", tempUser.getName());Assert.assertEquals("Surname is wrong!", "Messi", tempUser.getSurname());}/*** Tests the process of deleting user**/@Testpublic void deleteUser() {assertNotNullUserProperties(secondUser);Assert.assertTrue("User can not be added! User : " + secondUser, getUserService().addUser(secondUser));Assert.assertTrue("User can not be deleted! User : " + secondUser, getUserService().deleteUser(secondUser));}/*** Tests the process of updating user* @throws NonExistentUserException**/@Test(expectedExceptions = NonExistentUserException.class)public void updateUser() throws NonExistentUserException {getUserService().updateUser(thirdUser);}/*** Test user count**/@Testpublic void getUserCount() {Assert.assertEquals(1, getUserService().getUsers().size());}/*** The annotated method will be run after all the test methods in the current class have been run.**/@AfterClasspublic void afterClass() {logger.debug("AfterClass method is run...");}/*** The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run.**/@AfterTestpublic void afterTest() {logger.debug("AfterTest method is run...");}/*** The annotated method will be run after each test method.**/@AfterMethodpublic void afterMethod() {logger.debug("AfterMethod method is run...");}/*** Gets User Service** @return IUserService User Service*/public IUserService getUserService() {return userService;}/*** Sets User Service** @param IUserService User Service*/public void setUserService(IUserService userService) {this.userService = userService;}}

步骤10:创建applicationContext.xml

应用程序上下文的创建如下:

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><!-- User Map Declaration --><bean id="UserMap" class="java.util.concurrent.ConcurrentHashMap" /><!-- Cache Service Declaration --><bean id="CacheService" class="com.otv.cache.service.CacheService"><property name="userMap" ref="UserMap"/></bean><!-- User Service Declaration --><bean id="UserService" class="com.otv.user.service.UserService"><property name="cacheService" ref="CacheService"/></bean>
</beans>

步骤11:运行项目

在本文中,已使用TestNG Eclipse插件。 如果使用Eclipse,则可以通过TestNG下载页面下载它

如果运行UserServiceTester ,则测试用例的结果如下所示:

步骤12:下载

OTV_SpringTestNG

参考资料:
Spring测试支持
TestNG参考

参考: Online Technology Vision博客中的JCG合作伙伴 Eren Avsarogullari 提供的TestNG的Spring测试支持 。


翻译自: https://www.javacodegeeks.com/2012/05/spring-testing-support-with-testng.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/372433.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Entity Framework - 理清关系 - 基于外键关联的单向一对一关系

注&#xff1a;本文针对的是 Entity Framework Code First 场景。 之前写过三篇文章试图理清Entity Framework中的一对一关系&#xff08;单相思&#xff08;单向一对一&#xff09;, 两情相悦&#xff08;双向一对一&#xff09;, 两情相悦-续&#xff09;&#xff0c;但当时理…

微信社交小程序服务器,Day12-微信小程序实战-交友小程序-搭建服务器与上传文件到后端...

要搞一个小型的cms内容发布系统因为小程序上线之后&#xff0c;直接对数据库进行操作的话&#xff0c;慧出问题的&#xff0c;所以一般都会做一个管理系统&#xff0c;让工作人员通过这个管理系统来对这个数据库进行增删改查微信小程序其实给我们提供了这样的能力了(也就是可以…

java go

熟练掌握java技术&#xff0c;对多线程、数据结构有清晰的认识&#xff1b; 熟悉MySQL/Oracle数据库&#xff0c;熟悉关系数据库应用设计开发&#xff1b; 熟悉Spring/MyBatis/Freemarker等一种或者多种框架&#xff1b; java基础扎实&#xff0c;熟练掌握目前主流的开源框架&a…

了解如何解决OSGI捆绑包

我想回顾一下OSGI包如何解决并使用Apache Karaf进行演示。 Karaf是基于Apache Felix内核的功能齐全的OSGI容器&#xff0c;并且是Apache ServiceMix集成容器的基石。 对于第一部分&#xff0c;我将讨论OSGI框架如何解决捆绑包。 在第二部分中&#xff0c;我将使用Apache Karaf演…

文件共享服务器imac,iMac怎么在网络上共享设备windows文件夹和服务 | MOS86

本章通过向您展示如何在网络和Mac和Windows计算机之间共享文件&#xff0c;文件夹和设备&#xff0c;帮助您充分利用您的iMac网络连接。→使用Macs共享文件和文件夹使用AirDrop和文件共享→与Windows 7计算机共享文件→设置共享权限→使用共享表快速在线共享文件→共享和访问网…

【转】 简单理解Socket

题外话 前几天和朋友聊天&#xff0c;朋友问我怎么最近不写博客了&#xff0c;一个是因为最近在忙着公司使用的一些控件的开发&#xff0c;浏览器兼容性搞死人&#xff1b;但主要是因为这段时间一直在看html5的东西&#xff0c;看到web socket时觉得很有意思&#xff0c;动手写…

.NET基础

.NET C# ASP.NET关系&#xff1a;.NET是一个平台&#xff0c;提供程序运行的虚拟机环境和类库。 C#是.Net平台上的一种语言&#xff0c;其他语言还有VB.NET PowerShell等。 ASP.NET是在.NET下的网站开发技术。 安装.NET FrameWork就可以运行。VS集成安装了.NET FrameWork. 控制…

业务活动监视器(BAM)2.0带来的革命

生产兼具精益和企业价值的中间件是一项艰巨的工作。 它要么不存在&#xff0c;要么需要创新的思维&#xff08;很多&#xff09;&#xff0c;并且需要在实现中反复进行。 业务风险很大&#xff0c;但是如果您做对了&#xff0c;它就会使您领先于其他任何公司。 这就是为什么我们…

oracle销售服务器吗,oracle 服务器 版本

oracle 服务器 版本 内容精选换一换Atlas 800 训练服务器(型号 9010)安装上架、服务器基础参数配置、安装操作系统等操作请参见《Atlas 800 训练服务器 用户指南 (型号9010)》。Atlas 800 训练服务器(型号 9010)适配操作系统如表1所示。请参考表2下载驱动和固件包。Atlas 800 训…

Vue组件间通信:一个例子学会Vue组件-Vue.js学习总结)(转载)

详情请点击 http://www.jianshu.com/p/9ad1ba89a04b转载于:https://www.cnblogs.com/zhongjiang/p/6694459.html

必填字段的自定义JSF验证器

实现EditableValueHolder接口的JSF组件具有两个属性“ required”和“ requiredMessage” –一个标志&#xff0c;指示用户需要输入/选择非空值&#xff0c;以及一个用于验证消息的文本。 我们可以使用它&#xff0c;但是它不够灵活&#xff0c;我们不能直接在视图中&#xff0…

java 转码%2f%_JS和JAVA中常用的编码转码函数

js中escape,encodeURI,encodeURIComponent函数和unescape,decodeURI和decodeURIComponent函数的功能1.escape方法对String对象编码,escape方法返回一个包含了"转义序列"的字符串值。除了ASCII字母和数字&#xff0c;以及这几个符号 *-/._外(共有1052769个字符不会被编…

mybatis 下划线转驼峰配置

一直以来&#xff0c;在sqlmap文件中&#xff0c;对于数据库中的下划线字段转驼峰&#xff0c;我们都是通过resultmap来做的&#xff0c;如下&#xff1a; <resultMap id"ISTableStatistics" type"com.medsoft.perfstat.pojo.ISTableStatistics" > &…

Python练习-迭代器-模拟cat|grep文件

代码如下: 1 # 编辑者&#xff1a;闫龙2 def grep(FindWhat):3 fopen("a.txt","r",encoding"utf8")#以只读的方式打开a.txt文件4 while True:5 try:6 fline next(f).strip()#由于File类型本身就是一个迭代器,所以直…

Spring和JSF集成:转换器

使用任何Web框架时&#xff0c;都不可避免地需要将用户输入的数据从String为其他类型。 尽管Spring和JSF在设计和功能上确实有很大的不同&#xff0c;但它们都具有转换器策略来处理此问题。 让我们从春天开始。 Spring 3引入了一个全新的转换框架&#xff0c;该框架允许将任何类…

nacos配置ap_Nacos 1.0.0 功能预览

本文来自于我的个人主页&#xff1a;Nacos 1.0.0 功能预览&#xff0c;转载请保留链接 ;)Nacos 1.0.0 是正式 GA 的版本&#xff0c;在架构、功能和API设计上进行了全方位的重构和升级&#xff0c;1.0.0版本标志着Nacos的架构已经稳定&#xff0c;API列表最终确定。升级到1.0.0…

poj 2229 Sumsets

题目大意&#xff1a; 一个数由2的幂次数的和构成&#xff0c;问有几种构成方式&#xff1f; 主要是找规律 代码如下 1 #include <cstdio>2 #include <cstring>3 int n;4 #define M 10000000005 int dp[1000002];6 7 int main(int argc, char const *argv[])8 {9 …

html 甘特图_Rplotly|交互式甘特图(Gantt chart)项目管理/学习计划

甘特图(Gantt chart)&#xff0c;又常被称为横道图或者条状图&#xff0c;是现代企业项目管理领域运用最为广泛的一种图示。就是通过条形来显示项目的进度、时间安排等相关情况的。项目管理外&#xff0c;也可以用来管理学习计划。绘制甘特图的工具有很多&#xff0c;本文介绍使…

使您的Spring Security @Secured注释更干燥

最近&#xff0c;Grails用户邮件列表中的一个用户想知道在定义Secured批注时如何减少重复 。 在Java批注中指定属性的规则非常严格&#xff0c;因此我看不到直接执行他所要求的方法的方法。 使用Groovy并没有真正的帮助&#xff0c;因为Groovy类中的注释大部分与Java中的注释几…

阅读《大型网站技术架构》 第三章心得

今天阅读了《大型网站技术架构》 的第三章&#xff0c;这一章主要讲解了大型网站核心架构要素&#xff0c;并且概括的讲解了相应的实现方法。 软件架构除了系统功能需求外&#xff0c;还需要关注性能、可用性、伸缩性、扩展性、安全性。 其中性能是网站的重要指标。优化网站性能…