一.问题描述
在做自动化测试时,有两个测试方法,loginTrue方法和addUser方法,原则上只有loginTrue方法执行成功获取到cookie,并存储到TestConfig的静态对象cookiestore里面;下次从TestConfig拿到这个cookie请求addUser。
代码如下:
LoginTest类:
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.MybatisUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.SqlSession;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.URISyntaxException;
@Log4j2
public class LoginTest {
private CookieStore cookieStore;
@BeforeTest(groups = "loginTrue",description = "测试准备工作")
public void beforeTest(){
TestConfig.addUserUrl = ConfigFile.getUrl(InterfaceName.ADD_USER);
TestConfig.getUserInfoUrl = ConfigFile.getUrl(InterfaceName.GET_USER_INFO);
TestConfig.getUserListUrl = ConfigFile.getUrl(InterfaceName.GET_USER_LIST);
TestConfig.loginUrl = ConfigFile.getUrl(InterfaceName.LOGIN);
TestConfig.updateUserInfoUrl = ConfigFile.getUrl(InterfaceName.UPDATE_USER_INFO);
TestConfig.client = HttpClients.custom().setDefaultCookieStore(TestConfig.cookieStore).build();
}
@Test(groups = "loginTrue",description = "用户登录成功接口测试")
public void loginTrue() throws URISyntaxException {
SqlSession sqlSession = MybatisUtils.openSession();
LoginCase loginCase = sqlSession.selectOne("loginCase",1);
System.out.println(loginCase);
System.out.println(TestConfig.loginUrl);
log.info("********开始验证loginTrue api*********");
//发请求,获取结果
String result = getResult(loginCase,TestConfig.loginUrl);
log.info("请求http:localhost/v1/login的结果是------>" + result);
//验证返回结果
Assert.assertEquals(loginCase.getExpected(),result);
log.info("********loginTrue api 验证通过*********");
}
//getResult这个是具体发送请求的方法
private String getResult(LoginCase loginCase, String loginUrl) throws URISyntaxException {
//1.创建URLBuilder对象方法
URIBuilder uriBuilder = new URIBuilder(loginUrl);
uriBuilder.setParameter("userName",loginCase.getUserName()).setParameter("password",loginCase.getPassword());
//2.创建post方法
HttpPost post = new HttpPost(uriBuilder.build());
//3.获得client对象,并设置cookiestore
TestConfig.client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
//4.设置请求头
post.setHeader("content-type","application/json");
//5.设置cookie,已在3设置
//6.请求api,获得响应结果
CloseableHttpResponse response = null;
String res = null;
try {
response = TestConfig.client.execute(post);
res = EntityUtils.toString(response.getEntity(),"utf-8");
//7.存储cookies到TestConfig
log.info(cookieStore);
TestConfig.cookieStore = cookieStore;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
response.close();
TestConfig.client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//7.返回
return res;
}
@Test(groups = "loginFalse",description = "用户登录失败接口测试",enabled = false)
public void loginFalse() throws URISyntaxException {
SqlSession sqlSession = MybatisUtils.openSession();
LoginCase loginCase = sqlSession.selectOne("loginCase",2);
System.out.println(loginCase);
System.out.println(TestConfig.loginUrl);
log.info("********开始验证loginFalse api*********");
//发请求,获取结果
String result = getResult(loginCase,TestConfig.loginUrl);
log.info("请求http:localhost/v1/login的结果是------>" + result);
//验证返回结果
Assert.assertEquals(loginCase.getExpected(),result);
log.info("********loginFalse api 验证通过*********");
}
}
AddUserTest类
package com.course.cases;
import com.course.config.TestConfig;
import com.course.model.AddUserCase;
import com.course.utils.MybatisUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
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;
@Log4j2
public class AddUserTest {
@Test(dependsOnGroups = "loginTrue",description = "添加用户接口")
public void addUser(){
SqlSession sqlSession = MybatisUtils.openSession();
AddUserCase addUserCase = sqlSession.selectOne("addUser",1);
System.out.println(addUserCase);
System.out.println(TestConfig.addUserUrl);
log.info("********开始验证addUser api*********");
//发请求,获取结果
String result = getResult(addUserCase,TestConfig.addUserUrl);
log.info("请求http:localhost/v1/addUser的结果是------>" + result);
//验证返回结果
Assert.assertEquals(result,addUserCase.getExpected());
log.info("********addUser api 验证通过*********");
}
private String getResult(AddUserCase addUserCase,String testUrl){
//1.创建post方法
HttpPost post = new HttpPost(testUrl);
//2.获得client对象,并设置cookiestore(取自TestConfig)
TestConfig.client = HttpClients.custom().setDefaultCookieStore(TestConfig.cookieStore).build();
//3.JSONObject设置请求json数据,利用StringEntity携带在post请求里
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());
StringEntity entity = new StringEntity(param.toString(),"utf-8");
post.setEntity(entity);
//4.设置请求头
post.setHeader("content-type","application/json");
//5.设置cookie,已在2设置
//6.请求api,获得响应结果
CloseableHttpResponse response = null;
String res = "false";
try {
response = TestConfig.client.execute(post);
res = EntityUtils.toString(response.getEntity(),"utf-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
response.close();
TestConfig.client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//7.返回
return res;
}
}
运行testng.xml发现addUser方法运行失败,
二.问题解决
1.查看服务端报错日志
也就是说服务端进行校验的时候没有获取到cookie;
2.在AddUserTest里做断点调试,看下有没有拿到TestConfig的cookiestore
如图,拿到的cookiestore是null;
3.接着在LoginTest里做断点调试,看看是没有存储进去还是返回的response里面没有cookie信息
如图,response里面是包含cookie信息的,但是没有存储进cookiestore对象;
4.排查我的cookiestore代码,
由以下关键代码组成,
发现我只是声明了一个cookiestore对象,但是没有用new关键字实例化
5.修改代码如下:
6.再次调试运行LoginTest类,此时可以成功获取到cookie啦
7.再次运行自动化测试代码
11:46:02.125 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
11:46:02.128 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 1715248762.
11:46:02.128 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@663c9e7a]
11:46:02.128 [main] DEBUG com.course.model.addUser - ==> Preparing: select * from add_user_case where id=?
11:46:02.128 [main] DEBUG com.course.model.addUser - ==> Parameters: 1(Integer)
11:46:02.129 [main] DEBUG com.course.model.addUser - <== Total: 1
AddUserCase(id=1, userName=test1, password=111, age=11, sex=1, permission=1, isDelete=0, expected=true)
http://localhost:8080/v1/addUser
11:46:02.129 [main] INFO com.course.cases.AddUserTest - ********开始验证addUser api*********
11:46:02.137 [main] DEBUG org.apache.http.client.protocol.RequestAddCookies - CookieSpec selected: default
11:46:02.137 [main] DEBUG org.apache.http.client.protocol.RequestAddCookies - Cookie [version: 0][name: JSESSIONID][value: 080C66D4A4D30502096CBF692EE3E688][domain: localhost][path: /][expiry: null] match [localhost:8080/v1/addUser]
11:46:02.137 [main] DEBUG org.apache.http.client.protocol.RequestAddCookies - Cookie [version: 0][name: login][value: true][domain: localhost][path: /v1][expiry: null] match [localhost:8080/v1/addUser]
11:46:02.137 [main] DEBUG org.apache.http.client.protocol.RequestAuthCache - Auth cache not set in the context
11:46:02.137 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection request: [route: {}->http://localhost:8080][total kept alive: 0; route allocated: 0 of 2; total allocated: 0 of 20]
11:46:02.137 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection leased: [id: 1][route: {}->http://localhost:8080][total kept alive: 0; route allocated: 1 of 2; total allocated: 1 of 20]
11:46:02.138 [main] DEBUG org.apache.http.impl.execchain.MainClientExec - Opening connection {}->http://localhost:8080
11:46:02.138 [main] DEBUG org.apache.http.impl.conn.DefaultHttpClientConnectionOperator - Connecting to localhost/127.0.0.1:8080
11:46:02.138 [main] DEBUG org.apache.http.impl.conn.DefaultHttpClientConnectionOperator - Connection established 127.0.0.1:56145<->127.0.0.1:8080
11:46:02.138 [main] DEBUG org.apache.http.impl.execchain.MainClientExec - Executing request POST /v1/addUser HTTP/1.1
11:46:02.138 [main] DEBUG org.apache.http.impl.execchain.MainClientExec - Target auth state: UNCHALLENGED
11:46:02.138 [main] DEBUG org.apache.http.impl.execchain.MainClientExec - Proxy auth state: UNCHALLENGED
11:46:02.138 [main] DEBUG org.apache.http.headers - http-outgoing-1 >> POST /v1/addUser HTTP/1.1
11:46:02.138 [main] DEBUG org.apache.http.headers - http-outgoing-1 >> content-type: application/json
11:46:02.138 [main] DEBUG org.apache.http.headers - http-outgoing-1 >> Content-Length: 90
11:46:02.138 [main] DEBUG org.apache.http.headers - http-outgoing-1 >> Host: localhost:8080
11:46:02.138 [main] DEBUG org.apache.http.headers - http-outgoing-1 >> Connection: Keep-Alive
11:46:02.138 [main] DEBUG org.apache.http.headers - http-outgoing-1 >> User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_45)
11:46:02.138 [main] DEBUG org.apache.http.headers - http-outgoing-1 >> Cookie: JSESSIONID=080C66D4A4D30502096CBF692EE3E688; login=true
11:46:02.138 [main] DEBUG org.apache.http.headers - http-outgoing-1 >> Accept-Encoding: gzip,deflate
11:46:02.138 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "POST /v1/addUser HTTP/1.1[\r][\n]"
11:46:02.138 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "content-type: application/json[\r][\n]"
11:46:02.139 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "Content-Length: 90[\r][\n]"
11:46:02.139 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "Host: localhost:8080[\r][\n]"
11:46:02.139 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "Connection: Keep-Alive[\r][\n]"
11:46:02.139 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_45)[\r][\n]"
11:46:02.139 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "Cookie: JSESSIONID=080C66D4A4D30502096CBF692EE3E688; login=true[\r][\n]"
11:46:02.139 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "Accept-Encoding: gzip,deflate[\r][\n]"
11:46:02.139 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "[\r][\n]"
11:46:02.139 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "{"password":"111","isDelete":"0","sex":"1","permission":"1","userName":"test1","age":"11"}"
11:46:02.145 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "HTTP/1.1 200 [\r][\n]"
11:46:02.145 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Content-Type: application/json;charset=UTF-8[\r][\n]"
11:46:02.145 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Transfer-Encoding: chunked[\r][\n]"
11:46:02.148 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Date: Thu, 10 Jun 2021 03:46:02 GMT[\r][\n]"
11:46:02.148 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "[\r][\n]"
11:46:02.148 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "4[\r][\n]"
11:46:02.148 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "true[\r][\n]"
11:46:02.148 [main] DEBUG org.apache.http.headers - http-outgoing-1 << HTTP/1.1 200
11:46:02.148 [main] DEBUG org.apache.http.headers - http-outgoing-1 << Content-Type: application/json;charset=UTF-8
11:46:02.148 [main] DEBUG org.apache.http.headers - http-outgoing-1 << Transfer-Encoding: chunked
11:46:02.148 [main] DEBUG org.apache.http.headers - http-outgoing-1 << Date: Thu, 10 Jun 2021 03:46:02 GMT
11:46:02.148 [main] DEBUG org.apache.http.impl.execchain.MainClientExec - Connection can be kept alive indefinitely
11:46:02.148 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "0[\r][\n]"
11:46:02.148 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "[\r][\n]"
11:46:02.148 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection [id: 1][route: {}->http://localhost:8080] can be kept alive indefinitely
11:46:02.148 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection released: [id: 1][route: {}->http://localhost:8080][total kept alive: 1; route allocated: 1 of 2; total allocated: 1 of 20]
11:46:02.148 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection manager is shutting down
11:46:02.148 [main] DEBUG org.apache.http.impl.conn.DefaultManagedHttpClientConnection - http-outgoing-1: Close connection
11:46:02.148 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection manager shut down
11:46:02.148 [main] INFO com.course.cases.AddUserTest - 请求http:localhost/v1/addUser的结果是------>true
11:46:02.148 [main] INFO com.course.cases.AddUserTest - ********addUser api 验证通过*********
执行成功,数据库的user表成功添加数据
版权声明:本文为xun_zhao_t521原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。