日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

使用TestNG的弹簧测试支持

發(fā)布時(shí)間:2023/12/3 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用TestNG的弹簧测试支持 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
TestNG是一個(gè)測試框架,旨在涵蓋所有類別的測試:單元,功能,端到端,集成等。 它包括許多功能,例如靈活的測試配置,對數(shù)據(jù)驅(qū)動測試的支持(使用@DataProvider),強(qiáng)大的執(zhí)行模型(不再需要TestSuite)(等等)。

彈簧測試支持涵蓋了基于彈簧的應(yīng)用程序的單元和集成測試的非常有用和重要的功能。 org.springframework.test.context.testng包為基于TestNG的測試用例提供支持類。 本文展示了如何通過使用Spring和TestNG集成來測試Spring Service層組件。 下一篇文章還將展示如何使用相同的集成來測試Spring Data Access層組件。

二手技術(shù):

JDK 1.6.0_31
春天3.1.1
測試NG 6.4 Maven的3.0.2

步驟1:建立已完成的專案

如下創(chuàng)建一個(gè)Maven項(xiàng)目。 (可以使用Maven或IDE插件來創(chuàng)建它)。

步驟2:圖書館

Spring依賴項(xiàng)已添加到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:建立使用者類別

創(chuàng)建一個(gè)新的用戶類。

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:創(chuàng)建NonExistentUserException類

NonExistentUserException類已創(chuàng)建。

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步:創(chuàng)建ICacheService接口

創(chuàng)建了代表緩存服務(wù)接口的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:創(chuàng)建CacheService類

CacheService類是通過實(shí)現(xiàn)ICacheService接口創(chuàng)建的。 它提供對遠(yuǎn)程緩存的訪問…

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介面

創(chuàng)建了代表用戶服務(wù)接口的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:創(chuàng)建UserService類

通過實(shí)現(xiàn)IUserService接口創(chuàng)建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:創(chuàng)建UserServiceTester類

通過擴(kuò)展AbstractTestNGSpringContextTests創(chuàng)建用戶服務(wù)測試器類。

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:創(chuàng)建applicationContext.xml

應(yīng)用程序上下文的創(chuàng)建如下:

<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:運(yùn)行項(xiàng)目

在本文中,已使用TestNG Eclipse插件。 如果使用Eclipse,則可以通過TestNG下載頁面下載它

如果運(yùn)行UserServiceTester ,則測試用例的結(jié)果如下所示:

步驟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

總結(jié)

以上是生活随笔為你收集整理的使用TestNG的弹簧测试支持的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。