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

使用TestNG的弹簧测试支持相关推荐

  1. Spring测试支持和上下文缓存

    Spring为单元测试和集成测试提供了全面的支持-通过注释来加载Spring应用程序上下文,并与JUnit和TestNG等单元测试框架集成. 由于为每个测试加载大型应用程序上下文需要时间,因此Spri ...

  2. Go 语言新提案:添加模糊测试支持

    Go 语言增加了支持模糊测试 (Fuzz Test) 的新提案. 据介绍,此项提案会为 Go 添加新的testing.F类型,在_test.go文件中支持FuzzFoo函数,并增加新的go命令行为.该 ...

  3. Android 测试支持库 1.0 现已发布!

    我们非常高兴地宣布,Android 测试支持库 (ATSL) 1.0 版现已发布. ATSL 1.0 版对现有测试 API 进行了重要更新,不仅添加了许多新功能.还提升了性能和稳定性,同时还修复了若干 ...

  4. linux下webservice压力测试,pylot压力测试支持linux及windowsWebService性能及扩展性的工具.docx...

    pylot压力测试支持linux及windowsWebService性能及扩展性的工具 下载以下软件请加群292501151,群共享有如有不便敬请谅解,执行#后面跟着(linux命令行)!普:Pylo ...

  5. 腾讯 QQ 重新测试支持苹果 CallKit

    本文转载自IT之家 IT之家 8 月 17 日消息 据多位IT之家网友投稿,腾讯 QQ iOS 测试版 8.8.20 的部分用户开始测试支持苹果 CallKit. CallKit 是苹果在 iOS 1 ...

  6. GET和POST测试(支持需要登录的接口调用:高级功能-填写cookie)

    GET和POST测试(支持需要登录的接口调用:高级功能->填写cookie) http://coolaf.com/ 1.在一个需要抓取数据的网站,登录进入. 更改内核为charm,找到获取数据的 ...

  7. java持续集成soapui_集成testNG到JavaAPI测试-执行多条用例

    ***************************************************************** 在这门课里你将学到Web Services(SOAP WebServ ...

  8. Swift3的playground中对UI直接测试支持的改变

    我们知道在Xcode的playground中不仅可以测试console代码,还可以测试UI代码,甚至我们可以测试SpriteKit中的场景 而在本篇中我们只是简单聊一聊最新的Xcode8.0 beta ...

  9. 用maven搭建 testNG+PowerMock+Mockito测试框架

    转载:http://www.cnblogs.com/changzhz/p/5158068.html 单元测试是开发中必不可少的一部分,是产品代码的重要保证. Junit和testNG是当前最流行的测试 ...

最新文章

  1. 27. FormPanel类的defaults属性
  2. python基础知识点-Python入门基础知识点(基础语法介绍)
  3. bootstrap table php,bootstrap table Tooltip
  4. docker如何实现重新打tag并删除原tag的镜像([仓库名: tag] 可以查询到指定id的镜像,同一个id镜像能有多个[仓库名: tag])(增加\删除镜像仓库:标签)
  5. hibernate.hbm.xml详解
  6. matplotlib的默认字体_浅谈matplotlib默认字体设置探索
  7. 服务器配置列表在哪个文件夹,FolderMagic
  8. mac修改文件的默认打开方式
  9. 归并排序MergeSort
  10. 让程序像人一样的去批量下载歌曲?Python采集付费歌曲
  11. Ubuntu下rar带密码压缩/解压命令
  12. 毕业设计--20200228--内网搭建domoticz系统 frp内网穿透实现天猫精灵控制内网设备
  13. golang开发工程师-第一步:golang入门基础教学
  14. 论文写作:MATLAB+Visio生成不失真的PDF图像,同时解决MATLAB图像plot绘制有白边的问题
  15. 【70后、80后、90后嘚啵嘚】招募特约评论员啦!
  16. JavaScript插件编写
  17. 骨传导原理是什么?骨传导耳机的利弊
  18. 如何借用淘宝巧获海量精准流量?
  19. 做一条USB A转Type C 数据线 和OTG线
  20. 之江汇空间如何加音乐背景_之江汇互动课堂使用方法

热门文章

  1. jdk8 npe_JDK 14中更好的NPE消息
  2. maven原型_创建自定义Maven原型
  3. spring 构造函数注入_Spring构造函数依赖注入示例
  4. java8多线程运行程序_线程,代码和数据–多线程Java程序实际运行的方式
  5. rest资源设计_REST资源何时应获得其自己的地址?
  6. 笔试知识点 网络安全_安全点
  7. 愚弄dnn_不要被泛型和向后兼容性所愚弄。 使用泛型类型
  8. jboss 程序位置_介绍JBoss BPM Suite安装程序
  9. Java中的LinkedHashMap
  10. javafx 自定义控件_JavaFX自定义控件– Nest Thermostat第3部分