实现接口自动化测试代码。
注:这里测试的接口是spring boot开发接口中开发好的接口,只需运行application.java中的main方法,即可启动接口。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.coursegroupId>
<artifactId>requestTestartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
<version>4.1.2version>
dependency>
<dependency>
<groupId>org.jsongroupId>
<artifactId>jsonartifactId>
<version>20170516version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.17version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.16.14version>
dependency>
<dependency>
<groupId>com.relevantcodesgroupId>
<artifactId>extentreportsartifactId>
<version>2.41.1version>
dependency>
<dependency>
<groupId>com.vimalselvamgroupId>
<artifactId>testng-extentsreportartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>com.aventstackgroupId>
<artifactId>extentreportsartifactId>
<version>3.0.6version>
dependency>
<dependency>
<groupId>org.testnggroupId>
<artifactId>testngartifactId>
<version>6.10version>
dependency>
<dependency>
<groupId>commons-logginggroupId>
<artifactId>commons-loggingartifactId>
<version>1.1.1version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jpaartifactId>
<version>1.2.1.RELEASEversion>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-surefire-pluginartifactId>
<version>2.19.1version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>
src/main/resources/testng.xml
suiteXmlFile>
suiteXmlFiles>
configuration>
plugin>
plugins>
build>
project>
测试用例使用mysql数据库管理
测试用例 | 测试的接口 | 接口描述 |
---|---|---|
logincase | /v1/login | 登陆接口 |
getuserinfocase | /v1/getUserInfo | 获取用户信息接口 |
getuserlistcase | /v1/getUserInfo | 获取用户列表接口 |
addusercase | /v1/addUser | 添加用户接口 |
updateuserinfocase | /v1/updateUserInfo | 更新用户信息接口 |
databaseConfig.xml
<configuration>
<settings>
<setting name="localCacheScope" value="STATEMENT"/>
<setting name="cacheEnabled" value="false"/>
<setting name="logImpl" value="STDOUT_LOGGING" />
settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/course?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="mapper/SQLMapper.xml"/>
mappers>
configuration>
testng.xml
<suite name="用户管理系统测试套件">
<test name="用户管理系统测试用例">
test>
suite>
application.properties
test.url=http://localhost:8888
#登陆接口uri
login.uri=/v1/login
#更新用户信息接口uri
updateUserInfo.uri=/v1/updateUserInfo
#获取用户列表接口uri
getUserList.uri=/v1/getUserInfo
#获取用户信息接口uri
getUserInfo.uri=/v1/getUserInfo
#添加用户接口uri
addUser.uri=/v1/addUser
# 设置生成日志
logging.path=logs
logging.file=caseTest.log
AddUserCase.java
package com.course.model;
import lombok.Data;
/**
* 添加用户接口的测试用例
*/
@Data
public class AddUserCase {
private String userName;
private String password;
private String sex;
private String age;
private String permission;
private String isDelete;
private String expected;
}
GetUserInfoCase.java
package com.course.model;
import lombok.Data;
/**
* 获取用户信息的测试用例
*/
@Data
public class GetUserInfoCase {
private int userId;
private String expected;
}
GetUserListCase.java
package com.course.model;
import lombok.Data;
/**
* 获取用户列表
*/
@Data
public class GetUserListCase {
private String userName;
private String age;
private String sex;
private String expected;
}
InterfaceName.java
创建一个枚举类,对应接口的名称
package com.course.model;
/**
* 将需要测试的接口进行枚举,防止使用 测试范围外的非法接口
*/
public enum InterfaceName {
GETUSERLIST,LOGIN,UPDATEUSERINFO,GETUSERINFO,ADDUSERINFO
}
LoginCase.java
package com.course.model;
import lombok.Data;
/**
* 登录接口的测试用例
*/
@Data
public class LoginCase {
private int id;
private String userName;
private String password;
private String expected;
}
UpdateUserInfoCase.java
package com.course.model;
import lombok.Data;
/**
* 更新用户信息接口的测试用例
*/
@Data
public class UpdateUserInfoCase {
private int id;
private int userId;
private String userName;
private String sex;
private String age;
private String permission;
private String isDelete;
private String expected;
}
User.java
package com.course.model;
import lombok.Data;
/**
* 用户 Java Bean
*/
@Data
public class User {
private int id;
private String userName;
private String password;
private int age;
private String sex;
private int permission;
private int isDelete;
///复写toString方法,用来处理json
@Override
public String toString(){
return (
"id:"+id+","+
"userName:"+userName+","+
"password:"+password+","+
"age:"+age+","+
"sex:"+sex+","+
"permission:"+permission+","+
"isDelete:"+isDelete+"}"
);
}
}
ExtentTestNGIReporterListener.java
然后将报告加入监听
package com.course.config;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.ResourceCDN;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.model.TestAttribute;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;
import org.testng.*;
import org.testng.xml.XmlSuite;
import java.io.File;
import java.util.*;
public class ExtentTestNGIReporterListener implements IReporter {
//生成的路径以及文件名
private static final String OUTPUT_FOLDER = "test-output/";
private static final String FILE_NAME = "index.html";
private ExtentReports extent;
@Override
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
init();
boolean createSuiteNode = false;
if(suites.size()>1){
createSuiteNode=true;
}
for (ISuite suite : suites) {
Map<String, ISuiteResult> result = suite.getResults();
//如果suite里面没有任何用例,直接跳过,不在报告里生成
if(result.size()==0){
continue;
}
//统计suite下的成功、失败、跳过的总用例数
int suiteFailSize=0;
int suitePassSize=0;
int suiteSkipSize=0;
ExtentTest suiteTest=null;
//存在多个suite的情况下,在报告中将同一个一个suite的测试结果归为一类,创建一级节点。
if(createSuiteNode){
suiteTest = extent.createTest(suite.getName()).assignCategory(suite.getName());
}
boolean createSuiteResultNode = false;
if(result.size()>1){
createSuiteResultNode=true;
}
for (ISuiteResult r : result.values()) {
ExtentTest resultNode;
ITestContext context = r.getTestContext();
if(createSuiteResultNode){
//没有创建suite的情况下,将在SuiteResult的创建为一级节点,否则创建为suite的一个子节点。
if( null == suiteTest){
resultNode = extent.createTest(r.getTestContext().getName());
}else{
resultNode = suiteTest.createNode(r.getTestContext().getName());
}
}else{
resultNode = suiteTest;
}
if(resultNode != null){
resultNode.getModel().setName(suite.getName()+" : "+r.getTestContext().getName());
if(resultNode.getModel().hasCategory()){
resultNode.assignCategory(r.getTestContext().getName());
}else{
resultNode.assignCategory(suite.getName(),r.getTestContext().getName());
}
resultNode.getModel().setStartTime(r.getTestContext().getStartDate());
resultNode.getModel().setEndTime(r.getTestContext().getEndDate());
//统计SuiteResult下的数据
int passSize = r.getTestContext().getPassedTests().size();
int failSize = r.getTestContext().getFailedTests().size();
int skipSize = r.getTestContext().getSkippedTests().size();
suitePassSize += passSize;
suiteFailSize += failSize;
suiteSkipSize += skipSize;
if(failSize>0){
resultNode.getModel().setStatus(Status.FAIL);
}
resultNode.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;",passSize,failSize,skipSize));
}
buildTestNodes(resultNode,context.getFailedTests(), Status.FAIL);
buildTestNodes(resultNode,context.getSkippedTests(), Status.SKIP);
buildTestNodes(resultNode,context.getPassedTests(), Status.PASS);
}
if(suiteTest!= null){
suiteTest.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;",suitePassSize,suiteFailSize,suiteSkipSize));
if(suiteFailSize>0){
suiteTest.getModel().setStatus(Status.FAIL);
}
}
}
// for (String s : Reporter.getOutput()) {
// extent.setTestRunnerOutput(s);
// }
extent.flush();
}
private void init() {
//文件夹不存在的话进行创建
File reportDir= new File(OUTPUT_FOLDER);
if(!reportDir.exists()&& !reportDir .isDirectory()){
reportDir.mkdir();
}
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(OUTPUT_FOLDER + FILE_NAME);
//怎么样解决cdn.rawgit.com访问不了的情况?设置静态文件的DNS
htmlReporter.config().setResourceCDN(ResourceCDN.EXTENTREPORTS);
htmlReporter.config().setDocumentTitle("api自动化测试报告");
htmlReporter.config().setReportName("api自动化测试报告");
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.STANDARD);
htmlReporter.config().setCSS(".node.level-1 ul{ display:none;} .node.level-1.active ul{display:block;}");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setReportUsesManualConfiguration(true);
}
private void buildTestNodes(ExtentTest extenttest, IResultMap tests, Status status) {
//存在父节点时,获取父节点的标签
String[] categories=new String[0];
if(extenttest != null ){
List<TestAttribute> categoryList = extenttest.getModel().getCategoryContext().getAll();
categories = new String[categoryList.size()];
for(int index=0;index<categoryList.size();index++){
categories[index] = categoryList.get(index).getName();
}
}
ExtentTest test;
if (tests.size() > 0) {
//调整用例排序,按时间排序
Set<ITestResult> treeSet = new TreeSet<ITestResult>(new Comparator<ITestResult>() {
@Override
public int compare(ITestResult o1, ITestResult o2) {
return o1.getStartMillis()<o2.getStartMillis()?-1:1;
}
});
treeSet.addAll(tests.getAllResults());
for (ITestResult result : treeSet) {
Object[] parameters = result.getParameters();
String name="";
//如果有参数,则使用参数的toString组合代替报告中的name
for(Object param:parameters){
name+=param.toString();
}
if(name.length()>0){
if(name.length()>50){
name= name.substring(0,49)+"...";
}
}else{
name = result.getMethod().getMethodName();
}
if(extenttest==null){
test = extent.createTest(name);
}else{
//作为子节点进行创建时,设置同父节点的标签一致,便于报告检索。
test = extenttest.createNode(name).assignCategory(categories);
}
//test.getModel().setDescription(description.toString());
//test = extent.createTest(result.getMethod().getMethodName());
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
List<String> outputList = Reporter.getOutput(result);
for(String output:outputList){
//将用例的log输出报告中
test.debug(output);
}
if (result.getThrowable() != null) {
test.log(status, result.getThrowable());
}
else {
test.log(status, "Test " + status.toString().toLowerCase() + "ed");
}
test.getModel().setStartTime(getTime(result.getStartMillis()));
test.getModel().setEndTime(getTime(result.getEndMillis()));
}
}
}
private Date getTime(long millis) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
}
testng.xml
<listeners>
<listener class-name="com.course.config.ExtentTestNGIReporterListener">listener>
listeners>
创建TestConfig对象,对应application.properties中的接口名称
TestConfig.java
package com.course.config;
import lombok.Data;
import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
@Data
public class TestConfig {
//登陆接口uri
public static String loginUrl;
//更新用户信息接口uri
public static String updateUserInfoUrl;
//获取用户列表接口uri
public static String getUserListUrl;
//获取用户信息接口uri
public static String getUserInfoUrl;
//添加用户信息接口
public static String addUserUrl;
//声明http客户端
public static DefaultHttpClient defaultHttpClient;
//用来存储cookies信息的变量
public static CookieStore store;
}
注意:工具类里的对象、方法,我们一般声明为静态方法static,不用new,直接用。
ConfigFile.java
package com.course.utils;
import com.course.model.InterfaceName;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* 读取application.properties文件,拼接测试接口URL
*/
public class ConfigFile {
private static ResourceBundle bundle= ResourceBundle.getBundle("application", Locale.CHINA);;
//传进来的name,必须是我们设计的InterfaceName类中枚举的接口名,不能瞎传
public static String getUrl(InterfaceName name){
String address = bundle.getString("test.url");
String uri = ""; //获取application.perperties中的uri
String testUrl; //最终的测试地址,address+uri
if(name == InterfaceName.GETUSERLIST){
uri = bundle.getString("getUserList.uri");
}
if(name == InterfaceName.LOGIN){
uri = bundle.getString("login.uri");
}
if(name == InterfaceName.UPDATEUSERINFO){
uri = bundle.getString("updateUserInfo.uri");
}
if(name == InterfaceName.GETUSERINFO){
uri = bundle.getString("getUserInfo.uri");
}
if(name == InterfaceName.ADDUSERINFO){
uri = bundle.getString("addUser.uri");
}
testUrl = address + uri;
return testUrl;
}
}
创建连接数据库的session
DatabaseUtil.java
package com.course.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
/**
* 数据库工具类
*/
public class DatabaseUtil {
public static SqlSession getSqlSession() throws IOException {
//获取配置的资源文件
Reader reader = Resources.getResourceAsReader("databaseConfig.xml");
//得到SqlSessionFactory,使用类加载器加载xml文件
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
//得到sqlsession对象,这个对象就能执行配置文件中的sql语句啦
SqlSession session = factory.openSession();
return session;
}
}
package com.course.cases;
import com.course.config.TestConfig;
import com.course.model.AddUserCase;
import com.course.model.User;
import com.course.utils.DatabaseUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.SqlSession;
import org.json.JSONObject;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
public class AddUserTest {
//执行这个用例,前提需要登录成功!
//所以需要依赖登录成功那个组
@Test(dependsOnGroups = "loginTrue",description = "添加用户接口测试")
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void addUser() throws IOException, InterruptedException {
SqlSession session = DatabaseUtil.getSqlSession();
System.out.println(session);
AddUserCase addUserCase = session.selectOne("addUserCase", 1);
System.out.println("测试数据为:"+ addUserCase.toString());
System.out.println( "addUser的uri为:" + TestConfig.addUserUrl);
//发请求,获取结果
String result = getResult(addUserCase);
//验证返回结果
//session.commit();
/*
getResult调用接口,实际上是又开了一个进程,跟测试用例addUser()代码是并行运行的,
这个时候就需要让测试代码休息一下,等待接口调用完毕后,再去查数据库的结果,否则可能查出来user为null
*/
Thread.sleep(2000);
User user = session.selectOne("addUser", addUserCase); //sql:查看新增加的user
System.out.println("请求接口后,user表中新增的user为:" + user.toString());
//处理结果,判断返回结果是否符合预期
Assert.assertEquals(addUserCase.getExpected(), result);
}
private String getResult(AddUserCase addUserCase) throws IOException {
HttpPost post = new HttpPost(TestConfig.addUserUrl);
JSONObject param = new JSONObject();
param.put("userName", addUserCase.getUserName());
param.put("password", addUserCase.getPassword());
param.put("sex", addUserCase.getSex());
param.put("age", addUserCase.getAge());
param.put("permission", addUserCase.getPermission());
param.put("isDelete", addUserCase.getIsDelete());
//设置头信息
post.setHeader("content-type", "application/json");
StringEntity entity = new StringEntity(param.toString(), "utf-8");
post.setEntity(entity);
//设置cookies
TestConfig.defaultHttpClient.setCookieStore(TestConfig.store);
String result; //存放返回结果
HttpResponse response = TestConfig.defaultHttpClient.execute(post);
result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println("请求响应结果为:" + result);
return result;
}
}
GetUserInfoListTest.java
package com.course.cases;
import com.course.config.TestConfig;
import com.course.model.GetUserListCase;
import com.course.model.User;
import com.course.utils.DatabaseUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.SqlSession;
import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
public class GetUserInfoListTest {
@Test(dependsOnGroups = "loginTrue", description = "获取性别为男的用户信息")
public void getUserListInfo() throws IOException {
SqlSession session = DatabaseUtil.getSqlSession();
GetUserListCase getUserListCase = session.selectOne("getUserListCase", 1);
System.out.println(getUserListCase.toString());
System.out.println(TestConfig.getUserListUrl);
//第1步:发送请求,获取结果
//实际结果
JSONArray resultJSON = getJsonResult(getUserListCase);
//第2步:验证
List<User> userList = session.selectList(getUserListCase.getExpected(), getUserListCase);
for (User u: userList){
System.out.println("获取的user是" + u.toString());
}
//预期结果
JSONArray userListJson = new JSONArray(userList);
//判断获取用户的个数与预期是否相同
Assert.assertEquals(userListJson.length(), resultJSON.length());
//判断请求获取的每个用户信息与预期是否相同
for (int i = 0; i < resultJSON.length(); i++){
JSONObject expect = (JSONObject) resultJSON.get(i);
JSONObject actual = (JSONObject) userListJson.get(i);
Assert.assertEquals(expect.toString(), actual.toString());
}
}
private JSONArray getJsonResult(GetUserListCase getUserListCase) throws IOException {
HttpPost post = new HttpPost(TestConfig.getUserListUrl);
JSONObject param = new JSONObject(); //设置json数据
param.put("userName", getUserListCase.getUserName());
param.put("sex", getUserListCase.getSex());
param.put("age", getUserListCase.getAge());
post.setHeader("content-type", "application/json"); //设置header
StringEntity entity = new StringEntity(param.toString(), "utf-8");
post.setEntity(entity); //设置entity
TestConfig.defaultHttpClient.setCookieStore(TestConfig.store); //设置cookie
HttpResponse response = TestConfig.defaultHttpClient.execute(post);
String result = EntityUtils.toString(response.getEntity(), "utf-8");
JSONArray jsonArray = new JSONArray(result);
return jsonArray;
}
}
GetUserInfoTest.java
package com.course.cases;
import com.course.config.TestConfig;
import com.course.model.GetUserInfoCase;
import com.course.model.User;
import com.course.utils.DatabaseUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.SqlSession;
import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GetUserInfoTest {
@Test(dependsOnGroups = "loginTrue", description = "获取userId为1的用户信息")
public void getUerInfoTest() throws IOException {
SqlSession session = DatabaseUtil.getSqlSession();
GetUserInfoCase getUserInfoCase = session.selectOne("getUserInfoCase", 1);
System.out.println(getUserInfoCase.toString());
System.out.println(TestConfig.getUserInfoUrl);
//发送请求
//实际结果
JSONArray resultJSON = getJsonResult(getUserInfoCase);
//mapper id取getUserInfoCase中的expected字段,即获取预期的用户信息
User user = session.selectOne(getUserInfoCase.getExpected(), getUserInfoCase);
List userList = new ArrayList();
userList.add(user);
//预期结果
JSONArray jsonArray = new JSONArray(userList);
JSONArray jsonArray_res = new JSONArray(resultJSON.getString(0));
//jsonArray与jsonArray_res内元素顺序可能不同,不能这样断言;可以将里面每个元素取出,逐个断言
Assert.assertEquals(jsonArray.toString(), jsonArray_res.toString());
}
private JSONArray getJsonResult(GetUserInfoCase getUserInfoCase) throws IOException {
HttpPost post = new HttpPost(TestConfig.getUserInfoUrl);
JSONObject param = new JSONObject();
param.put("id", getUserInfoCase.getUserId());
post.setHeader("content-type", "application/json");
StringEntity entity = new StringEntity(param.toString(), "utf-8");
post.setEntity(entity);
TestConfig.defaultHttpClient.setCookieStore(TestConfig.store);
HttpResponse response = TestConfig.defaultHttpClient.execute(post);
String result = EntityUtils.toString(response.getEntity(), "utf-8");
List resultList = Arrays.asList(result);
JSONArray array = new JSONArray(resultList);
return array;
}
}
LoginTest.java
package com.course.cases;
import com.course.config.TestConfig;
import com.course.model.InterfaceName;
import com.course.model.LoginCase;
import com.course.utils.ConfigFile;
import com.course.utils.DatabaseUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.SqlSession;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
public class LoginTest {
@BeforeTest(groups = "loginTrue", description = "测试准备工作,获取httpclient对象")
public void beforeTest(){
TestConfig.getUserInfoUrl = ConfigFile.getUrl(InterfaceName.GETUSERINFO);
TestConfig.getUserListUrl = ConfigFile.getUrl(InterfaceName.GETUSERLIST);
TestConfig.addUserUrl = ConfigFile.getUrl(InterfaceName.ADDUSERINFO);
TestConfig.loginUrl = ConfigFile.getUrl(InterfaceName.LOGIN);
TestConfig.updateUserInfoUrl = ConfigFile.getUrl(InterfaceName.UPDATEUSERINFO);
TestConfig.defaultHttpClient = new DefaultHttpClient();
}
@Test(groups = "loginTrue", description = "用户登录成功接口测试")
public void loginTrue() throws IOException {
SqlSession session = DatabaseUtil.getSqlSession();
LoginCase loginCase = session.selectOne("loginCase", 1);//取xml文件中sql语句id为loginCase的,取数据库中id为1的数据
System.out.println(loginCase.toString());
System.out.println(TestConfig.loginUrl);
//第1步:发送请求
String result = getResult(loginCase);
System.out.println(result);
//验证结果
Assert.assertEquals(loginCase.getExpected(), result);
}
@Test(groups = "loginFalse", description = "用户登录失败接口测试")
public void loginFalse() throws IOException {
SqlSession session = DatabaseUtil.getSqlSession();
LoginCase loginCase = session.selectOne("loginCase", 2);//取xml文件中sql语句id为loginCase的,取数据库中id为2的数据
System.out.println(loginCase.toString());
System.out.println(TestConfig.loginUrl);
//第1步:发送请求
String result = getResult(loginCase);
System.out.println(result);
//验证结果
Assert.assertEquals(loginCase.getExpected(), result);
}
private String getResult(LoginCase loginCase) throws IOException {
HttpPost post = new HttpPost(TestConfig.loginUrl);
JSONObject param = new JSONObject();
param.put("userName", loginCase.getUserName());
param.put("password", loginCase.getPassword());
post.setHeader("content-type", "application/json");
StringEntity entity = new StringEntity(param.toString(), "utf-8");
post.setEntity(entity);
String result;
HttpResponse response = TestConfig.defaultHttpClient.execute(post);
result = EntityUtils.toString(response.getEntity(), "utf-8");
TestConfig.store = TestConfig.defaultHttpClient.getCookieStore();
return result;
}
}
UpdateUserInfoTest.java
package com.course.cases;
import com.course.config.TestConfig;
import com.course.model.UpdateUserInfoCase;
import com.course.model.User;
import com.course.utils.DatabaseUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.SqlSession;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
public class UpdateUserInfoTest {
@Test(dependsOnGroups = "loginTrue", description = "更改用户信息接口测试用例")
public void updateUserInfo() throws IOException, InterruptedException {
SqlSession session = DatabaseUtil.getSqlSession();
UpdateUserInfoCase updateUserInfoCase = session.selectOne("updateUserInfoCase", 1);
System.out.println(updateUserInfoCase.toString());
System.out.println(TestConfig.updateUserInfoUrl);
int result = getResult(updateUserInfoCase);
Thread.sleep(3000);
session.commit();
User user = session.selectOne(updateUserInfoCase.getExpected(), updateUserInfoCase);
//判断user不为空
Assert.assertNotNull(user);
//判断result不为空
Assert.assertNotNull(result);
}
@Test(dependsOnGroups = "loginTrue", description = "删除用户信息")
public void deleteUser() throws IOException, InterruptedException {
SqlSession session = DatabaseUtil.getSqlSession();
UpdateUserInfoCase updateUserInfoCase = session.selectOne("updateUserInfoCase", 2);
System.out.println(updateUserInfoCase.toString());
System.out.println(TestConfig.updateUserInfoUrl);
int result = getResult(updateUserInfoCase);
Thread.sleep(3000);
session.commit();
User user = session.selectOne(updateUserInfoCase.getExpected(), updateUserInfoCase);
//判断user不为空
Assert.assertNotNull(user);
Assert.assertNotNull(result);
}
private int getResult(UpdateUserInfoCase updateUserInfoCase) throws IOException {
HttpPost post = new HttpPost(TestConfig.updateUserInfoUrl);
//设置请求json
JSONObject param = new JSONObject();
param.put("id", updateUserInfoCase.getUserId());
param.put("userName", updateUserInfoCase.getUserName());
param.put("sex", updateUserInfoCase.getSex());
param.put("age", updateUserInfoCase.getAge());
param.put("permission", updateUserInfoCase.getPermission());
param.put("isDelete", updateUserInfoCase.getIsDelete());
//设置请求头信息
post.setHeader("content-type", "application/json");
//设置请求实体
StringEntity entity = new StringEntity(param.toString(), "utf-8");
post.setEntity(entity);
//设置cookie
TestConfig.defaultHttpClient.setCookieStore(TestConfig.store);
String result;
HttpResponse response = TestConfig.defaultHttpClient.execute(post);
result = EntityUtils.toString(response.getEntity(), "utf-8");
return Integer.parseInt(result);
}
}
SQLMapper.xml
<mapper namespace="com.course.model">
<select id="loginCase" parameterType="Integer" resultType="com.course.model.LoginCase">
select * from loginCase
where id = #{id};
select>
<select id="addUserCase" parameterType="Integer" resultType="com.course.model.AddUserCase">
select * from addUserCase where id=#{id};
select>
<select id="getUserInfoCase" parameterType="Integer" resultType="com.course.model.GetUserInfoCase">
select * from getUserInfoCase where id=#{id};
select>
<select id="getUserListCase" parameterType="Integer" resultType="com.course.model.GetUserListCase">
select * from getUserListCase where id=#{id};
select>
<select id="updateUserInfoCase" parameterType="Integer" resultType="com.course.model.UpdateUserInfoCase">
select * from updateUserInfoCase where id = #{id};
select>
<select id="addUser" parameterType="com.course.model.AddUserCase" resultType="com.course.model.User" flushCache="false" useCache="false">
select * from user where
userName=#{userName}
and password=#{password}
and sex=#{sex}
and age=#{age}
and permission=#{permission}
and isDelete=#{isDelete};
select>
<select id="getUserInfo" parameterType="com.course.model.GetUserInfoCase" resultType="com.course.model.User">
select * from user where
id=#{userId};
select>
<select id="getUserList" parameterType="com.course.model.GetUserListCase" resultType="com.course.model.User">
select * from user
<trim prefix="WHERE" prefixOverrides="and">
<if test="null != userName and '' !=userName">
AND userName=#{userName}
if>
<if test="null != sex and '' !=sex">
AND sex=#{sex}
if>
<if test="null != age and '' !=age">
AND age=#{age}
if>
trim>
;
select>
<select id="getUpdateUserInfo" parameterType="com.course.model.UpdateUserInfoCase" resultType="com.course.model.User">
select * from user
<trim prefix="WHERE" prefixOverrides="and">
<if test="null != userName and '' !=userName">
AND userName=#{userName}
if>
<if test="null != sex and '' !=sex">
AND sex=#{sex}
if>
<if test="null != age and '' !=age">
AND age=#{age}
if>
<if test="null != permission and '' !=permission">
AND permission=#{permission}
if>
<if test="null != isDelete and '' !=isDelete">
AND isDelete=#{isDelete}
if>
trim>
And id = #{userId};
select>
mapper>
testng.xml
<suite name="用户管理系统测试套件">
<test name="用户管理系统测试用例">
<classes>
<class name="com.course.cases.LoginTest">
<methods>
<include name="loginTrue"/>
methods>
class>
<class name="com.course.cases.AddUserTest">
<methods>
<include name="addUser"/>
methods>
class>
<class name="com.course.cases.GetUserInfoTest">
<methods>
<include name="getUserInfo"/>
methods>
class>
<class name="com.course.cases.GetUserInfoListTest">
<methods>
<include name="getUserListInfo"/>
methods>
class>
<class name="com.course.cases.UpdateUserInfoTest">
<methods>
<include name="updateUserInfo"/>
<include name="deleteUser"/>
methods>
class>
<class name="com.course.cases.wangTest">
<methods>
<include name="wangGetUser"/>
methods>
class>
classes>
test>
<listeners>
<listener class-name="com.course.config.ExtentTestNGIReporterListener">listener>
listeners>
suite>
在terminal中,进入项目目录下,执行mvn clean package
,所有测试用例执行成功的情况下,会在target目录下生成jar包
注:我这里项目名称由requestTest改为interfaceTest了,大家进入自己的项目路径就可以。