一.接口开发

1.引入依赖

1

2 org.springframework.boot

3 spring-boot-starter-parent

4 1.5.3.RELEASE

5

6

7 org.springframework.boot

8 spring-boot-starter-web

9

10

11

12 io.springfox

13 springfox-swagger-ui

14 2.6.1

15

16

17

18 io.springfox

19 springfox-swagger2

20 2.6.1

21

22

23

24 org.projectlombok

25 lombok

26 1.16.14

27

28

29

30 com.alibaba

31 fastjson

32 1.2.38

33

34

35

36 mysql

37 mysql-connector-java

38

39

40

41 org.mybatis.spring.boot

42 mybatis-spring-boot-starter

43 1.3.0

44

2.application.yml文件配置

1 server:2 port: 8888

3

4 spring:5 application:6 name: userManager7 datasource:8 driver-class-name: com.mysql.jdbc.Driver9 url: jdbc:mysql://localhost:3306/test

10 username: root11 password: admin330612

13 mybatis:14 type-aliases-package: com.test.pojo15 mapper-locations:16 - mapper/*

3.新建mapper包,包下新建SQLMapper.xml

1 <?xml version="1.0" encoding="UTF-8"?>

2 /p>

4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

5

6

7

8 select count(*) from user where username=#{username} and password=#{password};9

10

11

12 insert into13 user(username,password,sex,age,permisson,isDelete)14 values15 (#{username},#{password},#{sex},#{age},#{permisson},#{isDelete});16

17

18

22

23 select *from user24

25

26 AND id=#{id}27

28

29 AND username=#{username}30

31

32 AND password=#{password}33

34

35 AND age=#{age}36

37

38 AND sex=#{sex}39

40

41 AND permisson=#{permisson}42

43

44 AND isDelete=#{isDelete}45

46

47

48

49

50

51 update user52

53

54 username=#{username},55

56

57 password=#{password},58

59

60 age=#{age},61

62

63 sex=#{sex},64

65

66 permisson=#{permisson},67

68

69 isDelete=#{isDelete},70

71

72 where id=#{id};73

74

4.mybatis-config.xml文件配置

1 <?xml version="1.0" encoding="UTF-8" ?>

2

3 /p>

5 "http://mybatis.org/dtd/mybatis-3-config.dtd">

6

7

8

9

10

11

12

13

14

5.logback配置

1 <?xml version="1.0" encoding="UTF-8"?>

2

4 xsi:noNamespaceSchemaLocation="http://www.padual.com/java/logback.xsd"

5 debug="false" scan="true" scanPeriod="30 second">

6

7

8

9

10

11

12

13

14

15 [%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n16

17

18

19

20

21

22 [%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n23

24

25

26 ERROR

27 ACCEPT

28 DENY

29

30

31 ${ROOT}%d/error.%i.log

32 ${MAXHISTORY}

33

35 ${FILESIZE}

36

37

38

39

40

41

42

43 [%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n44

45

46

47 WARN

48 ACCEPT

49 DENY

50

51

52 ${ROOT}%d/warn.%i.log

53 ${MAXHISTORY}

54

55 ${FILESIZE}

56

57

58

59

60

61

62

63 [%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n64

65

66

67 INFO

68 ACCEPT

69 DENY

70

71

72 ${ROOT}%d/info.%i.log

73 ${MAXHISTORY}

74

75 ${FILESIZE}

76

77

78

79

80

81

82 [%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n83

84

85

86 DEBUG

87 ACCEPT

88 DENY

89

90

91 ${ROOT}%d/debug.%i.log

92 ${MAXHISTORY}

93

95 ${FILESIZE}

96

97

98

99

100

101

102 [%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n103

104

105

106 TRACE

107 ACCEPT

108 DENY

109

110

112 ${ROOT}%d/trace.%i.log

113 ${MAXHISTORY}

114

116 ${FILESIZE}

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

6.新建实体类User

1 packagecom.test.pojo;2

3 importlombok.Data;4

5 @Data6 public classUser {7 private intid;8 privateString username;9 privateString password;10 private intage;11 private intsex;12 private intpermisson;13 private intisDelete;14

15 }

7.新建SwaggerConfig

1 packagecom.test.config;2

3 importorg.springframework.context.annotation.Bean;4 importorg.springframework.context.annotation.Configuration;5 importspringfox.documentation.builders.ApiInfoBuilder;6 importspringfox.documentation.builders.PathSelectors;7 importspringfox.documentation.service.ApiInfo;8 importspringfox.documentation.service.Contact;9 importspringfox.documentation.spi.DocumentationType;10 importspringfox.documentation.spring.web.plugins.Docket;11 importspringfox.documentation.swagger2.annotations.EnableSwagger2;12

13 @Configuration14 @EnableSwagger215 public classSwaggerConfig {16 @Bean17 publicDocket api(){18 return newDocket(DocumentationType.SWAGGER_2)19 .apiInfo(apiInfo())20 .pathMapping("/")21 .select()22 .paths(PathSelectors.regex("/.*"))23 .build();24 }25

26 privateApiInfo apiInfo() {27 return new ApiInfoBuilder().title("UserManager service API")28 .version("1.0")29 .build();30 }31 }

8.编写verifyCookies工具类

1 packagecom.test.utils;2

3 importjavax.servlet.http.Cookie;4 importjavax.servlet.http.HttpServletRequest;5

6 importlombok.extern.log4j.Log4j;7 @Log4j8 public classCookiesUtil {9 public staticBoolean verifyCookies(HttpServletRequest request) {10 Cookie[] cookie=request.getCookies();11 if (cookie ==null) {12 log.info("cookies为空");13 return false;14 }15 for(Cookie c:cookie) {16 if (c.getName().equals("login")&&c.getValue().equals("true")) {17 log.info("cookies验证通过");18 return true;19 }20 }21 return false;22 }23

24 }

9.新建controller,接口开发代码

1 packagecom.test.controller;2

3 importjava.util.List;4

5 importjavax.servlet.http.Cookie;6 importjavax.servlet.http.HttpServletRequest;7 importjavax.servlet.http.HttpServletResponse;8

9 importorg.mybatis.spring.SqlSessionTemplate;10 importorg.springframework.beans.factory.annotation.Autowired;11 importorg.springframework.web.bind.annotation.PostMapping;12 importorg.springframework.web.bind.annotation.RequestBody;13 importorg.springframework.web.bind.annotation.RequestMapping;14 importorg.springframework.web.bind.annotation.RestController;15

16 importcom.test.pojo.User;17 importcom.test.utils.CookiesUtil;18

19 importio.swagger.annotations.Api;20 importio.swagger.annotations.ApiOperation;21 importlombok.extern.log4j.Log4j;22 @Log4j23 @RestController24 @Api(value = "/v1",description = "用户管理系统")25 @RequestMapping("/v1")26 public classUserMananger {27 @Autowired28 privateSqlSessionTemplate template;29

30 @ApiOperation(value = "登录接口")31 @PostMapping("/login")32 publicBoolean login(HttpServletResponse response,@RequestBody User user) {33 int i=template.selectOne("login",user);34 if (i==1) {35 Cookie cookie= new Cookie("login", "true");36 response.addCookie(cookie);37 log.info("登录的用户是:"+user.getUsername());38 return true;39 }40 return false;41 }42

43 @ApiOperation(value = "添加用户接口")44 @PostMapping("/addUser")45 publicBoolean addUser(HttpServletRequest request,@RequestBody User user) {46 Boolean b=CookiesUtil.verifyCookies(request);47 int i=0;48 if(b) {49 i= template.insert("addUser",user);50 }51 if (i>0) {52 log.info("添加用户的数量是:"+i);53 return true;54 }55 return false;56 }57

58 @ApiOperation(value = "获取用户(列表)信息接口")59 @PostMapping("/getUserInfo")60 public ListgetUserInfo(HttpServletRequest request,@RequestBody User user){61 Boolean b =CookiesUtil.verifyCookies(request);62 if(b) {63 List users =template.selectList("getUserInfo",user);64 log.info("getUserInfo获取到的用户数量是"+users.size());65 returnusers;66 }67 return null;68 }69

70 @ApiOperation(value = "更新删除用户接口")71 @PostMapping("/updateUser")72 public intupdateUser(HttpServletRequest request,@RequestBody User user) {73 boolean b =CookiesUtil.verifyCookies(request);74 int i=0;75 if(b) {76 i=template.update("updateUser",user);77

78 }79 log.info("更新数据的条目数为:"+i);80 returni;81 }82

83 }

10.新建springboot启动类

packagecom.test;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling

@SpringBootApplicationpublic classApplication {public static voidmain(String[] args) {

SpringApplication.run(Application.class,args);

}

}

11.目录结构图

二.测试代码开发

1.新建一个maven工程,引入依赖

1

2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

3 4.0.0

4

5 org.springframework.boot

6 spring-boot-starter-parent

7 1.5.3.RELEASE

8

9 com.test.autotest

10 Charpter12

11 0.0.1-SNAPSHOT

12 jar

13

14 Charpter12

15 http://maven.apache.org

16

17

18 UTF-8

19

20

21

22

23 org.apache.httpcomponents

24 httpclient

25 4.1.2

26

27

28 org.json

29 json

30 20170516

31

32

33 org.mybatis.spring.boot

34 mybatis-spring-boot-starter

35 1.3.0

36

37

38 org.mybatis

39 mybatis

40 3.4.4

41

42

43 mysql

44 mysql-connector-java

45 5.1.6

46

47

48 org.projectlombok

49 lombok

50 1.16.14

51

52

53

54 com.relevantcodes

55 extentreports

56 2.41.1

57

58

59 com.vimalselvam

60 testng-extentsreport

61 1.3.1

62

63

64 com.aventstack

65 extentreports

66 3.0.6

67

68

69

70 org.testng

71 testng

72 6.10

73

74

75 commons-logging

76 commons-logging

77 1.2

78

79

80 org.springframework.boot

81 spring-boot-starter-web

82 1.5.3.RELEASE

83

84

85 io.springfox

86 springfox-swagger2

87 2.6.1

88

89

90 io.springfox

91 springfox-swagger-ui

92 2.6.1

93

94

95

2.application.properties配置

1 test.url=http://localhost:8888

2

3 #登陆接口4 login.uri=/v1/login5

6 #更新用户信息接口7 updateUserInfo.uri=/v1/updateUserInfo8

9 #获取用户列表接口10 getUserList.uri=/v1/getUserInfo11

12 #获取用户信息接口13 getUserInfo.uri=/v1/getUserInfo14

15 #添加用户接口16 addUser.uri=/v1/addUser

3.mybatis.xml配置

1 <?xml version="1.0" encoding="UTF-8"?>

2 /p>

3 "http://mybatis.org/dtd/mybatis-3-config.dtd">

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

4.新建mapper包,包下新建SQLMapper.xml

1 <?xml version="1.0" encoding="UTF-8"?>

2 /p>

3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

4

5

6

7

8 select *from loginCase9 where id=#{id};10

11

12

13

14 select * from addusercase where id =#{id};15

16

17

18

19 select *from user where20 username =#{username}21 and password=#{password}22 and sex=#{sex}23 and age=#{age}24 and permisson=#{permisson}25 and isDelete=#{isDelete};26

27

28

29

30 select * from getuserinfocase where id=#{id};31

32

33

34

35 select *from user where36 id=#{userid};37

38

39

40

41 select * from getuserlistcase where id=#{id};42

43

44

45

46 select *from user47

48

49 AND username=#{username}50

51

52 AND sex=#{sex}53

54

55 AND age=#{age}56

57

58 ;59

60

61

62

63 select * from updateuserinfocase where id=#{id};64

65

66

67

68 select *from user69

70

71 AND username=#{username}72

73

74 AND sex=#{sex}75

76

77 AND age=#{age}78

79

80 AND permisson=#{permisson}81

82

83 AND isDelete=#{isDelete}84

85

86 And id =#{userid}87

88

5.logback配置

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="http://www.padual.com/java/logback.xsd"debug="false" scan="true" scanPeriod="30 second">

[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n

[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n

ERROR

ACCEPT

DENY

${ROOT}%d/error.%i.log

${MAXHISTORY}

${FILESIZE}

[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n

WARN

ACCEPT

DENY

${ROOT}%d/warn.%i.log

${MAXHISTORY}

${FILESIZE}

[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n

INFO

ACCEPT

DENY

${ROOT}%d/info.%i.log

${MAXHISTORY}

${FILESIZE}

[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n

DEBUG

ACCEPT

DENY

${ROOT}%d/debug.%i.log

${MAXHISTORY}

${FILESIZE}

[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n

TRACE

ACCEPT

DENY

${ROOT}%d/trace.%i.log

${MAXHISTORY}

${FILESIZE}

6.与数据库对应的实体类

1 packagecom.test.pojo;2

3 importlombok.Data;4

5 @Data6 public classAddUserCase {7 privateString username;8 privateString password;9 private intsex;10 private intage;11 private intpermisson;12 private intisDelete;13 privateString expected;14 }

1 packagecom.test.pojo;2

3 importlombok.Data;4

5 @Data6 public classGetUserInfoCase {7

8 private intuserid;9 privateString expected;10 }

1 packagecom.test.pojo;2

3 importlombok.Data;4

5 @Data6 public classGetUserListCase {7 privateString username;8 private intage;9 private intsex;10 privateString expected;11

12 }

1 packagecom.test.pojo;2

3 public enumInterfaceName {4 GETUSERLIST,LOGIN,UPDATEUSERINFO,GETUSERINFO,ADDUSERINFO5 }

1 packagecom.test.pojo;2

3 importlombok.Data;4

5 @Data6 public classLoginCase {7 private intid;8 privateString username;9 privateString password;10 privateString expected;11

12 }

1 packagecom.test.pojo;2

3

4 importlombok.Data;5

6 @Data7 public classUpdateUserInfoCase {8 private intid;9 private intuserid;10 privateString username;11 private intsex;12 private intage;13 private intpermisson;14 private intisDelete;15 privateString expected;16 }

packagecom.test.pojo;importlombok.Data;

@Datapublic classUser {private intid;privateString username;privateString password;private intage;private intsex;private intpermisson;private intisDelete;

@OverridepublicString toString(){return("{id:"+id+","+

"userName:"+username+","+

"password:"+password+","+

"age:"+age+","+

"sex:"+sex+","+

"permission:"+permisson+","+

"isDelete:"+isDelete+"}");

}

}

7.工具类设计

1 packagecom.test.utils;2

3 importjava.util.Locale;4 importjava.util.ResourceBundle;5

6 importcom.test.pojo.InterfaceName;7

8 public classConfigFile {9

10 private static ResourceBundle bundle = ResourceBundle.getBundle("application", Locale.CHINA);11

12 public staticString getUrl(InterfaceName name){13 String address = bundle.getString("test.url");14 String uri="";15 //最终的测试地址

16 String testUrl;17

18 if(name ==InterfaceName.GETUSERLIST){19 uri = bundle.getString("getUserList.uri");20 }21

22 if(name ==InterfaceName.LOGIN){23 uri = bundle.getString("login.uri");24 }25

26 if(name ==InterfaceName.UPDATEUSERINFO){27 uri = bundle.getString("updateUserInfo.uri");28 }29

30 if(name ==InterfaceName.GETUSERINFO){31 uri = bundle.getString("getUserInfo.uri");32 }33

34 if(name ==InterfaceName.ADDUSERINFO){35 uri = bundle.getString("addUser.uri");36 }37

38 testUrl = address +uri;39 returntestUrl;40 }41

42 }

1 packagecom.test.utils;2

3 importorg.apache.ibatis.io.Resources;4 importorg.apache.ibatis.session.SqlSession;5 importorg.apache.ibatis.session.SqlSessionFactory;6 importorg.apache.ibatis.session.SqlSessionFactoryBuilder;7

8 importjava.io.IOException;9 importjava.io.Reader;10

11 public classDatabaseUtil {12

13 public static SqlSession getSqlSession() throwsIOException {14 //获取配置的资源文件

15 Reader reader = Resources.getResourceAsReader("mybatis.xml");16

17 SqlSessionFactory factory = newSqlSessionFactoryBuilder().build(reader);18 //sqlSession就是能够执行配置文件中的sql语句。

19 SqlSession sqlSession =factory.openSession();20

21 returnsqlSession;22 }23

24 }

8.配置类设计

1 packagecom.test.config;2

3 importorg.apache.http.client.CookieStore;4 importorg.apache.http.impl.client.DefaultHttpClient;5

6 public classTestConfig {7 public staticString loginUrl;8 public staticString updateUserInfoUrl;9 public staticString getUserListUrl;10 public staticString getUserInfoUrl;11 public staticString addUserUrl;12

13

14 public staticDefaultHttpClient defaultHttpClient;15 public staticCookieStore store;16

17 }

1 packagecom.test.config;2

3

4 importcom.aventstack.extentreports.ExtentReports;5 importcom.aventstack.extentreports.ExtentTest;6 importcom.aventstack.extentreports.ResourceCDN;7 importcom.aventstack.extentreports.Status;8 importcom.aventstack.extentreports.model.TestAttribute;9 importcom.aventstack.extentreports.reporter.ExtentHtmlReporter;10 importcom.aventstack.extentreports.reporter.configuration.ChartLocation;11 importcom.aventstack.extentreports.reporter.configuration.Theme;12 import org.testng.*;13 importorg.testng.xml.XmlSuite;14

15 importjava.io.File;16 import java.util.*;17

18 public class ExtentTestNGIReporterListener implementsIReporter {19 //生成的路径以及文件名

20 private static final String OUTPUT_FOLDER = "test-output/";21 private static final String FILE_NAME = "extend_report.html";22

23 privateExtentReports extent;24

25 @Override26 public void generateReport(List xmlSuites, Listsuites, String outputDirectory) {27 init();28 boolean createSuiteNode = false;29 if(suites.size()>1){30 createSuiteNode=true;31 }32 for(ISuite suite : suites) {33 Map result =suite.getResults();34 //如果suite里面没有任何用例,直接跳过,不在报告里生成

35 if(result.size()==0){36 continue;37 }38 //统计suite下的成功、失败、跳过的总用例数

39 int suiteFailSize=0;40 int suitePassSize=0;41 int suiteSkipSize=0;42 ExtentTest suiteTest=null;43 //存在多个suite的情况下,在报告中将同一个一个suite的测试结果归为一类,创建一级节点。

44 if(createSuiteNode){45 suiteTest =extent.createTest(suite.getName()).assignCategory(suite.getName());46 }47 boolean createSuiteResultNode = false;48 if(result.size()>1){49 createSuiteResultNode=true;50 }51 for(ISuiteResult r : result.values()) {52 ExtentTest resultNode;53 ITestContext context =r.getTestContext();54 if(createSuiteResultNode){55 //没有创建suite的情况下,将在SuiteResult的创建为一级节点,否则创建为suite的一个子节点。

56 if( null ==suiteTest){57 resultNode =extent.createTest(r.getTestContext().getName());58 }else{59 resultNode =suiteTest.createNode(r.getTestContext().getName());60 }61 }else{62 resultNode =suiteTest;63 }64 if(resultNode != null){65 resultNode.getModel().setName(suite.getName()+" : "+r.getTestContext().getName());66 if(resultNode.getModel().hasCategory()){67 resultNode.assignCategory(r.getTestContext().getName());68 }else{69 resultNode.assignCategory(suite.getName(),r.getTestContext().getName());70 }71 resultNode.getModel().setStartTime(r.getTestContext().getStartDate());72 resultNode.getModel().setEndTime(r.getTestContext().getEndDate());73 //统计SuiteResult下的数据

74 int passSize =r.getTestContext().getPassedTests().size();75 int failSize =r.getTestContext().getFailedTests().size();76 int skipSize =r.getTestContext().getSkippedTests().size();77 suitePassSize +=passSize;78 suiteFailSize +=failSize;79 suiteSkipSize +=skipSize;80 if(failSize>0){81 resultNode.getModel().setStatus(Status.FAIL);82 }83 resultNode.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;",passSize,failSize,skipSize));84 }85 buildTestNodes(resultNode,context.getFailedTests(), Status.FAIL);86 buildTestNodes(resultNode,context.getSkippedTests(), Status.SKIP);87 buildTestNodes(resultNode,context.getPassedTests(), Status.PASS);88 }89 if(suiteTest!= null){90 suiteTest.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;",suitePassSize,suiteFailSize,suiteSkipSize));91 if(suiteFailSize>0){92 suiteTest.getModel().setStatus(Status.FAIL);93 }94 }95

96 }97 //for (String s : Reporter.getOutput()) {98 //extent.setTestRunnerOutput(s);99 //}

100

101 extent.flush();102 }103

104 private voidinit() {105 //文件夹不存在的话进行创建

106 File reportDir= newFile(OUTPUT_FOLDER);107 if(!reportDir.exists()&& !reportDir .isDirectory()){108 reportDir.mkdir();109 }110 ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(OUTPUT_FOLDER +FILE_NAME);111 //设置静态文件的DNS112 //怎么样解决cdn.rawgit.com访问不了的情况

113 htmlReporter.config().setResourceCDN(ResourceCDN.EXTENTREPORTS);114

115 htmlReporter.config().setDocumentTitle("api自动化测试报告");116 htmlReporter.config().setReportName("api自动化测试报告");117 htmlReporter.config().setChartVisibilityOnOpen(true);118 htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);119 htmlReporter.config().setTheme(Theme.STANDARD);120 htmlReporter.config().setCSS(".node.level-1 ul{ display:none;} .node.level-1.active ul{display:block;}");121 extent = newExtentReports();122 extent.attachReporter(htmlReporter);123 extent.setReportUsesManualConfiguration(true);124 }125

126 private voidbuildTestNodes(ExtentTest extenttest, IResultMap tests, Status status) {127 //存在父节点时,获取父节点的标签

128 String[] categories=new String[0];129 if(extenttest != null){130 List categoryList =extenttest.getModel().getCategoryContext().getAll();131 categories = newString[categoryList.size()];132 for(int index=0;index

137 ExtentTest test;138

139 if (tests.size() > 0) {140 //调整用例排序,按时间排序

141 Set treeSet = new TreeSet(new Comparator() {142 @Override143 public intcompare(ITestResult o1, ITestResult o2) {144 return o1.getStartMillis()

152 for(Object param:parameters){153 name+=param.toString();154 }155 if(name.length()>0){156 if(name.length()>50){157 name= name.substring(0,49)+"...";158 }159 }else{160 name =result.getMethod().getMethodName();161 }162 if(extenttest==null){163 test =extent.createTest(name);164 }else{165 //作为子节点进行创建时,设置同父节点的标签一致,便于报告检索。

166 test =extenttest.createNode(name).assignCategory(categories);167 }168 //test.getModel().setDescription(description.toString());169 //test = extent.createTest(result.getMethod().getMethodName());

170 for(String group : result.getMethod().getGroups())171 test.assignCategory(group);172

173 List outputList =Reporter.getOutput(result);174 for(String output:outputList){175 //将用例的log输出报告中

176 test.debug(output);177 }178 if (result.getThrowable() != null) {179 test.log(status, result.getThrowable());180 }181 else{182 test.log(status, "Test " + status.toString().toLowerCase() + "ed");183 }184

185 test.getModel().setStartTime(getTime(result.getStartMillis()));186 test.getModel().setEndTime(getTime(result.getEndMillis()));187 }188 }189 }190

191 private Date getTime(longmillis) {192 Calendar calendar =Calendar.getInstance();193 calendar.setTimeInMillis(millis);194 returncalendar.getTime();195 }196 }

9.测试代码设计

1 packagecom.test.cases;2

3 importjava.io.IOException;4

5 importorg.apache.http.HttpResponse;6 importorg.apache.http.client.methods.HttpPost;7 importorg.apache.http.entity.StringEntity;8 importorg.apache.http.impl.client.DefaultHttpClient;9 importorg.apache.http.util.EntityUtils;10 importorg.apache.ibatis.session.SqlSession;11 importorg.json.JSONObject;12 importorg.testng.Assert;13 importorg.testng.annotations.BeforeTest;14 importorg.testng.annotations.Test;15

16 importcom.test.config.TestConfig;17 importcom.test.pojo.InterfaceName;18 importcom.test.pojo.LoginCase;19 importcom.test.utils.ConfigFile;20 importcom.test.utils.DatabaseUtil;21

22 public classLoginTest {23

24 @BeforeTest(groups = "loginTrue",description = "测试准备工作,获取HttpClient对象")25 public voidbeforeTest(){26 TestConfig.getUserInfoUrl =ConfigFile.getUrl(InterfaceName.GETUSERINFO);27 TestConfig.getUserListUrl =ConfigFile.getUrl(InterfaceName.GETUSERLIST);28 TestConfig.addUserUrl =ConfigFile.getUrl(InterfaceName.ADDUSERINFO);29 TestConfig.loginUrl =ConfigFile.getUrl(InterfaceName.LOGIN);30 TestConfig.updateUserInfoUrl =ConfigFile.getUrl(InterfaceName.UPDATEUSERINFO);31 TestConfig.defaultHttpClient = newDefaultHttpClient();32 }33

34 @Test(groups = "loginTrue",description = "用户登陆成功接口测试")35 public void loginTrue() throwsIOException {36 SqlSession session =DatabaseUtil.getSqlSession();37 LoginCase loginCase = session.selectOne("loginCase",1);38 //发送请求

39 String result =getResult(loginCase);40 //验证结果

41 Assert.assertEquals(loginCase.getExpected(),result);42

43 }44 @Test(groups = "loginFalse",description = "用户登陆失败接口测试")45 public void loginFalse() throwsIOException {46 SqlSession session =DatabaseUtil.getSqlSession();47 LoginCase loginCase = session.selectOne("loginCase",2);48 //发送请求

49 String result =getResult(loginCase);50 //验证结果

51 Assert.assertEquals(loginCase.getExpected(),result);52

53 }54

55

56

57 private String getResult(LoginCase loginCase) throwsIOException {58 HttpPost post = newHttpPost(TestConfig.loginUrl);59 JSONObject param = newJSONObject();60 param.put("username",loginCase.getUsername());61 param.put("password",loginCase.getPassword());62 post.setHeader("content-type","application/json");63 StringEntity entity = new StringEntity(param.toString(),"utf-8");64 post.setEntity(entity);65 String result;66 HttpResponse response =TestConfig.defaultHttpClient.execute(post);67 result = EntityUtils.toString(response.getEntity(),"utf-8");68 TestConfig.store =TestConfig.defaultHttpClient.getCookieStore();69 returnresult;70 }71 }

1 packagecom.test.cases;2

3 importjava.io.IOException;4

5 importorg.apache.http.HttpResponse;6 importorg.apache.http.client.ClientProtocolException;7 importorg.apache.http.client.methods.HttpPost;8 importorg.apache.http.entity.StringEntity;9 importorg.apache.http.util.EntityUtils;10 importorg.apache.ibatis.session.SqlSession;11 importorg.json.JSONObject;12 importorg.testng.Assert;13 importorg.testng.annotations.Test;14

15 importcom.test.config.TestConfig;16 importcom.test.pojo.AddUserCase;17 importcom.test.pojo.User;18 importcom.test.utils.DatabaseUtil;19

20 public classAddUserTest {21

22 @Test(dependsOnGroups = "loginTrue",description = "添加用户接口测试")23 public void addUser() throwsIOException, InterruptedException {24 SqlSession session =DatabaseUtil.getSqlSession();25 AddUserCase addUserCase = session.selectOne("addUserCase",2);26 //发送请求

27 String result =getResult(addUserCase);28 //Thread.sleep(5000);29 //User user = session.selectOne("addUser",addUserCase);30 //System.out.println(user.toString());31 //验证结果

32 Assert.assertEquals(addUserCase.getExpected(),result);33 }34

35 private String getResult(AddUserCase addUserCase) throwsClientProtocolException, IOException {36 HttpPost post = newHttpPost(TestConfig.addUserUrl);37 JSONObject param = newJSONObject();38 param.put("username",addUserCase.getUsername());39 param.put("password",addUserCase.getPassword());40 param.put("age",addUserCase.getAge());41 param.put("sex",addUserCase.getSex());42 param.put("permisson",addUserCase.getPermisson());43 param.put("isDelete",addUserCase.getIsDelete());44 post.setHeader("content-type","application/json");45 StringEntity entity = new StringEntity(param.toString(),"utf-8");46 post.setEntity(entity);47 //设置cookies

48 TestConfig.defaultHttpClient.setCookieStore(TestConfig.store);49 String result;50 HttpResponse response =TestConfig.defaultHttpClient.execute(post);51 result = EntityUtils.toString(response.getEntity(),"utf-8");52 returnresult;53 }54 }

1 packagecom.test.cases;2

3 importjava.io.IOException;4 importjava.util.Arrays;5 importjava.util.List;6

7 importorg.apache.http.HttpResponse;8 importorg.apache.http.client.ClientProtocolException;9 importorg.apache.http.client.methods.HttpPost;10 importorg.apache.http.entity.StringEntity;11 importorg.apache.http.util.EntityUtils;12 importorg.apache.ibatis.session.SqlSession;13 importorg.json.JSONArray;14 importorg.json.JSONObject;15 importorg.testng.Assert;16 importorg.testng.annotations.Test;17

18 importcom.test.config.TestConfig;19 importcom.test.pojo.GetUserInfoCase;20 importcom.test.pojo.GetUserListCase;21 importcom.test.pojo.User;22 importcom.test.utils.DatabaseUtil;23

24 public classGetUserInfoListTest {25 @Test(dependsOnGroups = "loginTrue",description = "获取sex为0的用户信息")26 public void getUserInfoList() throwsIOException {27 SqlSession session =DatabaseUtil.getSqlSession();28 GetUserListCase getUserListCase = session.selectOne("getUserInfoListCase",1);29 JSONArray resultJson=getJsonResult(getUserListCase);30 System.out.println(resultJson.toString());31 //验证

32 List users =session.selectList(getUserListCase.getExpected(), getUserListCase);33 JSONArray array = newJSONArray(users);34 System.out.println(array.toString());35 Assert.assertEquals(array.length(), resultJson.length());36 for (int i = 0; i < resultJson.length(); i++) {37 JSONObject actual=(JSONObject) array.get(i);38 JSONObject except=(JSONObject) resultJson.get(i);39 Assert.assertEquals(actual.toString(), except.toString());40 }41 }42

43 private JSONArray getJsonResult(GetUserListCase getUserListCase) throwsClientProtocolException, IOException {44 HttpPost post = newHttpPost(TestConfig.getUserListUrl);45 JSONObject param = newJSONObject();46 param.put("sex",getUserListCase.getSex());47 post.setHeader("content-type","application/json");48 StringEntity entity = new StringEntity(param.toString(),"utf-8");49 post.setEntity(entity);50 //设置cookies

51 TestConfig.defaultHttpClient.setCookieStore(TestConfig.store);52 String result;53 HttpResponse response =TestConfig.defaultHttpClient.execute(post);54 result = EntityUtils.toString(response.getEntity(),"utf-8");55 JSONArray array = newJSONArray(result);56 returnarray;57 }58 }

1 packagecom.test.cases;2

3 importjava.io.IOException;4 importjava.util.ArrayList;5 importjava.util.Arrays;6 importjava.util.List;7

8 importorg.apache.http.HttpResponse;9 importorg.apache.http.client.ClientProtocolException;10 importorg.apache.http.client.methods.HttpPost;11 importorg.apache.http.entity.StringEntity;12 importorg.apache.http.util.EntityUtils;13 importorg.apache.ibatis.session.SqlSession;14 importorg.json.JSONArray;15 importorg.json.JSONObject;16 importorg.testng.Assert;17 importorg.testng.annotations.Test;18

19 importcom.test.config.TestConfig;20 importcom.test.pojo.GetUserInfoCase;21 importcom.test.pojo.User;22 importcom.test.utils.DatabaseUtil;23

24 public classGetUserInfoTest {25 @Test(dependsOnGroups = "loginTrue",description = "获取userid为1的用户信息")26 public void getUserInfo() throwsIOException {27 SqlSession session =DatabaseUtil.getSqlSession();28 GetUserInfoCase getUserInfoCase = session.selectOne("getUserInfoCase",1);29 JSONArray resultJson =getJsonResult(getUserInfoCase);30 User user=session.selectOne(getUserInfoCase.getExpected(), getUserInfoCase);31 System.out.println(user);32 List users= new ArrayList();33 users.add(user);34 JSONArray jsonArray = newJSONArray(users);35 JSONArray jsonArray1 = new JSONArray(resultJson.getString(0));36 Assert.assertEquals(jsonArray.toString(),jsonArray1.toString());37 }38

39 private JSONArray getJsonResult(GetUserInfoCase getUserInfoCase) throwsClientProtocolException, IOException {40 HttpPost post = newHttpPost(TestConfig.getUserInfoUrl);41 JSONObject param = newJSONObject();42 param.put("id",getUserInfoCase.getUserid());43 post.setHeader("content-type","application/json");44 StringEntity entity = new StringEntity(param.toString(),"utf-8");45 post.setEntity(entity);46 //设置cookies

47 TestConfig.defaultHttpClient.setCookieStore(TestConfig.store);48 String result;49 HttpResponse response =TestConfig.defaultHttpClient.execute(post);50 result = EntityUtils.toString(response.getEntity(),"utf-8");51 List resultList =Arrays.asList(result);52 JSONArray array = newJSONArray(resultList);53 returnarray;54 }55 }

1 packagecom.test.cases;2

3 importjava.io.IOException;4 importjava.util.ArrayList;5 importjava.util.List;6

7 importorg.apache.http.HttpResponse;8 importorg.apache.http.client.ClientProtocolException;9 importorg.apache.http.client.methods.HttpPost;10 importorg.apache.http.entity.StringEntity;11 importorg.apache.http.util.EntityUtils;12 importorg.apache.ibatis.session.SqlSession;13 importorg.json.JSONArray;14 importorg.json.JSONObject;15 importorg.testng.Assert;16 importorg.testng.annotations.Test;17

18 importcom.test.config.TestConfig;19 importcom.test.pojo.UpdateUserInfoCase;20 importcom.test.pojo.User;21 importcom.test.utils.DatabaseUtil;22

23 public classUpdateUserInfoTest {24 @Test(dependsOnGroups = "loginTrue",description = "更改用户信息")25 public void updateUser() throwsIOException, InterruptedException {26 SqlSession session =DatabaseUtil.getSqlSession();27 UpdateUserInfoCase updateUserInfoCase =session.selectOne("updateUserInfoCase", 1);28 int result =getResult(updateUserInfoCase);29 User user =session.selectOne(updateUserInfoCase.getExpected(), updateUserInfoCase);30 Assert.assertNotNull(user);31 Assert.assertNotNull(result);32 }33 @Test(dependsOnGroups = "loginTrue",description = "删除用户信息")34 public void deleteUser() throwsIOException, InterruptedException {35 SqlSession session =DatabaseUtil.getSqlSession();36 UpdateUserInfoCase updateUserInfoCase =session.selectOne("updateUserInfoCase", 2);37 int result =getResult(updateUserInfoCase);38 User user =session.selectOne(updateUserInfoCase.getExpected(), updateUserInfoCase);39 Assert.assertNotNull(user);40 Assert.assertNotNull(result);41 }42

43 private int getResult(UpdateUserInfoCase updateUserInfoCase) throwsClientProtocolException, IOException, InterruptedException {44 HttpPost post = newHttpPost(TestConfig.updateUserInfoUrl);45 JSONObject param = newJSONObject();46 param.put("username",updateUserInfoCase.getUsername());47 param.put("sex",updateUserInfoCase.getSex());48 param.put("age",updateUserInfoCase.getAge());49 param.put("permisson",updateUserInfoCase.getPermisson());50 param.put("isDelete",updateUserInfoCase.getIsDelete());51 param.put("id",updateUserInfoCase.getUserid());52 post.setHeader("content-type","application/json");53 StringEntity entity = new StringEntity(param.toString(),"utf-8");54 post.setEntity(entity);55 //设置cookies

56 TestConfig.defaultHttpClient.setCookieStore(TestConfig.store);57 String result;58 HttpResponse response =TestConfig.defaultHttpClient.execute(post);59 result = EntityUtils.toString(response.getEntity(),"utf-8");60 System.out.println(result);61 Thread.sleep(10000);62 returnInteger.parseInt(result);63 }64

65 }

10.testng.xml配置

11.运行接口工厂中的springboot类,启动后,运行测试代码中的testng.xml,运行结束后可以看到测试报告

12.目录结构图

13.git地址:https://github.com/pancakefans/AutoTest.git

java系统接口开发_模拟用户管理系统java接口开发与测试实战相关推荐

  1. php网页抓取浏览者手机号码_微信小程序开发之获取用户手机号码(php接口解密)...

    后边要做一个微信小程序,并要能获取用户微信绑定的手机号码.而小程序开发文档上边提供的获取手机号码的接口(getPhoneNumber())返回的是密文,需要服务器端进行解密,但是官方提供的开发文档一如 ...

  2. 31:第三章:开发通行证服务:14:开发【获得用户基本信息,接口】;(需要根据前端对返回数据的要求,创建一个只包含非隐私信息的AppUserVO类,去包装返回给前端的数据)

    说明: (1)本篇博客内容:开发[获得用户基本信息,接口]: 目录 零:本篇博客合理性说明:(或者说是:[获得用户基本信息,接口]是什么) 一:正式开发: 1.在[api]接口工程的UserContr ...

  3. Java语言程序设计 :医院简易挂号管理系统 Java实验

    Java语言程序设计 :医院简易挂号管理系统 Java实验 1.课程设计目的 医院预约挂号管理系统是每一个医疗机构管理平常挂号业务流程不可或缺的一个管理信息系统,它的存在解决了病人挂号难.看病难等问题 ...

  4. java接口开发_如果你想学好Java,这些你需要了解

    01基本知识 在学习Java之前,您需要了解计算机的基本知识,然后再学习Java.同时,您需要熟悉DOS命令.Java概述.JDK环境安装配置.环境变量配置.JDK和环境变量配置完成后,就可以编写Ja ...

  5. python接口自动化测试框架实战从设计到开发_【B0753】[java视频教程]Python接口自动化测试框架设计到开发完整版视频教程 it教程...

    Java视频教程名称:Python接口自动化测试框架设计到开发完整版视频教程   java自学网[javazx.com]  Python视频教程   it教程 Java自学网收集整理 java论坛&q ...

  6. java接口版本控制_为什么要在Java中控制类和接口的可见性

    java接口版本控制 维护是软件开发的重要方面之一,并且经验证明,保持较低组件可视性的软件比暴露更多组件的软件更易于维护. 您不会在一开始就意识到它,但是在重新设计应用程序时会严重错过它. 由于保持向 ...

  7. 李兴华java视频在线观看_李兴华Java开发实战经典视频教程_IT教程网

    资源名称:李兴华Java开发实战经典视频教程 资源目录: [IT教程网]010201_[第2章:简单Java程序]_简单Java程序 [IT教程网]010301_[第3章:Java基础程序设计]_Ja ...

  8. SSH整合开发实例:用户管理系统

    本文使用的是Struts2+Hibernate3+Spring3框架整合开发的用户管理系统实例. 1.1数据库层实现 建数据库,名为surra: 建数据表,名为user.其中id设置为自增. 1.2H ...

  9. api接口优化_使用电池状态API优化开发

    api接口优化 Imagine if you could program your app to adapt to the end user's device - such as turning of ...

最新文章

  1. Javaweb中提到的反射浅析(附源码)
  2. SVN冲突出现原因及解决方法浅谈
  3. 【计算机组成原理】定点数的表示和运算
  4. irq4中断子程序c语言写法,AVR汇编程序参考
  5. mysql事务基础+基于innodb的行锁+间隙锁+如何锁定行
  6. iOS实现字符串动画
  7. 知识整理(你想要的Linux知识都在这里)
  8. jquery blockui 遮罩【转】
  9. WebRTC手册(一)
  10. 使用Sharepoint Services 3.0构建基本网站
  11. 一步步的Abaqus2021版本安装教程+汉化操作
  12. 智能算法之免疫算法求解TSP问题
  13. 3、FFmpeg 过滤器
  14. 分享一款免费刷相关搜索、联想下拉推荐、网页快照排名的软件
  15. 流媒体协议(三):FLV协议
  16. 人名按照首字母排序c语言,c语言按中文姓名排序问题
  17. c++我的世界小游戏
  18. ie9 java小程序设置_小程序 自定义导航栏
  19. 想哪写哪_随笔20191130
  20. 斗鱼直播Android开发二面被刷,不吃透都对不起自己

热门文章

  1. python os.system保存返回值_python中os.system的返回值
  2. android友盟埋点,React Native 的友盟统计--打点/埋点
  3. Oh!兄嘚,想要提高技能?先从锁的优化开始吧
  4. 关于bat中set /p=前面加空格的bug修复方法
  5. ROS2机器人实验报告提示01➡入梦⬅
  6. 通过脚本自由设计游戏UI风格
  7. to B和to C产品的区别
  8. CCC3.0学习笔记_SCP03安全通道
  9. 【视频分享】尚硅谷Java视频教程_Spring注解驱动开发视频教程
  10. 人生需要认真思考的一些故事