【八:(调springboot+testng+mybatis+数据校验】

目录

    • 1、代码结构
      • config
      • controller
      • model
      • springboot启动类
    • 2、配置资源
      • mysql.xml
      • application.yml
      • logback.xml
      • mybatis-config.xml
      • 数据库配置
    • 3、测试验证

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AEG8EeLC-1721979102842)(https://i-blog.csdnimg.cn/blog_migrate/56ffafdae87ae3a6d3f93b5df03ab35d.png)]

1、代码结构

config

package com.course.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .pathMapping("/")
                .select()
                .paths(PathSelectors.regex("/.*"))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("UserManager service API")
                .contact(new Contact("dazhou", "", "42197393@qq.com"))
                .description("this is UserManager service API")
                .version("1.0")
                .build();
    }
}

controller

package com.course.controller;

import com.course.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;


@Log4j
@RestController
@Api(value = "v1",tags = "用户管理系统")
@RequestMapping("v1")
public class UserManager {


    //首先获取一个执行sql语句的对象
    @Autowired
    private SqlSessionTemplate template;

    @ApiOperation(value = "登陆接口",httpMethod = "POST")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Boolean login(HttpServletResponse response, @RequestBody User user){
        //拿过user来到数据库里面插,是不是有这个用户
        //login01需要和mysql.xml中 <!--登陆接口sql-->中的id一致
        int i  = template.selectOne("login01",user);
        //如果有就成功返回对应的cookies信息 login:true
        Cookie cookie = new Cookie("login","true");
        response.addCookie(cookie);
        log.info("查看到的结果是"+i);
        if(i==1){
            return true;
        }
        return false;
    }
    @ApiOperation(value = "添加用户接口",httpMethod = "POST")
    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    public boolean addUser(HttpServletRequest request,@RequestBody User user){
        Boolean x = verifyCookies(request);
        int result = 0;
        if(x != null){
            result = template.insert("addUser",user);
        }
        if(result>0){
            log.info("添加用户的数量是:"+result);
            return true;
        }
        return false;
    }

    private Boolean verifyCookies(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if(Objects.isNull(cookies)){
            log.info("cookies为空");
            return false;
        }
        for(Cookie cookie : cookies){
            if(cookie.getName().equals("login") &&
                    cookie.getValue().equals("true")){
                log.info("cookies验证通过");
                return true;
            }
        }
        return false;
    }

    @ApiOperation(value = "获取用户(列表)信息接口",httpMethod = "POST")
    @RequestMapping(value = "/getUserInfo",method = RequestMethod.POST)
    public List<User> getUserInfo(HttpServletRequest request,@RequestBody User user){
        Boolean x = verifyCookies(request);
        if(x==true){
            List<User> users = template.selectList("getUserInfo",user);
            log.info("getUserInfo获取到的用户数量是" +users.size());
            return users;
        }else {
            return null;
        }
    }


    @ApiOperation(value = "更新/删除用户接口",httpMethod = "POST")
    @RequestMapping(value = "/updateUserInfo",method = RequestMethod.POST)
    public int updateUser(HttpServletRequest request,@RequestBody User user){
        Boolean x = verifyCookies(request);
        int i = 0;
        if(x==true) {
            i = template.update("updateUserInfo", user);
        }
        log.info("更新数据的条目数为:" + i);
        return i;

    }


}

model

package com.course.model;

import lombok.Data;

@Data
public class User {
    private int id;
    private String userName;
    private String password;
    private String age;
    private String sex;
    private String permission;
    private String isDelete;
}

springboot启动类

package com.course;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.annotation.PreDestroy;

@EnableScheduling
@SpringBootApplication
public class Application {

    private  static ConfigurableApplicationContext context;

    public static void main(String[] args) {
        Application.context = SpringApplication.run(Application.class,args);
    }

    @PreDestroy
    public void close(){
        Application.context.close();
    }

}

2、配置资源

mysql.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.course">
  <!--登陆接口sql-->
  <select id="login01" parameterType="com.course.model.User" resultType="Integer">
    select count(*) from user
    where userName=#{userName}
    and password=#{password}
  </select>

  <!--添加用户接口-->
  <insert id="addUser" parameterType="com.course.model.User">
    insert into
    user (userName,password,sex,age,permission,isDelete)
    values (#{userName},#{password},#{sex},#{age},#{permission},#{isDelete});
  </insert>

  <!--获取用户信息sql-->
  <select id="getUserInfo" parameterType="com.course.model.User" resultType="com.course.model.User">
    select * from user
    <trim prefix="WHERE" prefixOverrides="and">
      <if test="null != id and '' !=id">
        AND id=#{id}
      </if>
      <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>
  </select>


  <!--更新/删除用户信息动作-->
  <update id="updateUserInfo" parameterType="com.course.model.User">
    update user
    <trim prefix="SET" suffixOverrides=",">
      <if test="null != userName and '' !=userName">
        userName=#{userName},
      </if>
      <if test="null != sex and '' !=sex">
        sex=#{sex},
      </if>
      <if test="null != age and '' !=age">
        age=#{age},
      </if>
      <if test="null != permission and '' !=permission">
        permission=#{permission},
        </if>
        <if test="null != isDelete and '' !=isDelete">
        isDelete=#{isDelete},
        </if>
        </trim>
        where id = #{id}
        </update>

        </mapper>

application.yml

server:
   port: 8888

logging:
    # 日志文件的路径
    path: logs
    file:
      # 日志文件的名字
      name: mylog.log
    pattern:
      # file 是指日志文件中日志的格式
      console: "%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger{50}- %msg%n"
      file: "%d{yyyy/MM/dd-HH:mm:ss} ---- [%thread] %-5level %logger{50}- %msg%n"

spring:
   application:
          name: report
   datasource:
       driver-class-name: com.mysql.jdbc.Driver
       url: jdbc:mysql://localhost:3306/course
       username: root
       password: 123456

mybatis:
    type-aliases-package: com.course.model
    mapper-locations:
       - mapper/*

logback.xml

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

    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <property name="FILE_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{80} - %msg%n"/>
    <property name="LOG_PATH" value="${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}"/>
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_PATH}/${LOG_FILE}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_PATH}/${LOG_FILE}.%d{yyyy-MM-dd}</fileNamePattern>
        </rollingPolicy>
        <encoder charset="UTF-8">
            <pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>
    </appender>


    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>
    </appender>


    <appender name="CRAWLER_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_PATH}/event.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_PATH}/event.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>30</maxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%msg%n</pattern>
        </encoder>
    </appender>


    <logger name="com.business.intelligence.util.CrawlerLogger" level="INFO" additivity="false">
        <appender-ref ref="CRAWLER_LOG"/>
    </logger>

    <root level="INFO">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE"/>
    </root>


</configuration>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <typeAliases>
        <package name="com.course.model"/>
    </typeAliases>
    <mappers>
        <mapper resource="mapper/mysql.xml"/>
    </mappers>
</configuration>

数据库配置

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Zsqieh2Y-1721979102844)(https://i-blog.csdnimg.cn/blog_migrate/c0df8f0f6c71e5cdd331ee84a2d235db.png)]

3、测试验证

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UvIrfHUj-1721979102845)(https://i-blog.csdnimg.cn/blog_migrate/c6af57c0deac4ba963d8f9eb6cb9b782.png)]

可以看到返回值为true了,说明已经在数据库查到相对于的数据了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot和TestNG是两个独立的技术,可以结合使用来实现自动化测试。下面是一个实现Spring Boot和TestNG自动化测试的步骤: 1. 首先,确保你已经安装了Java和Maven,并且已经创建了一个Spring Boot项目。 2. 在项目的pom.xml文件中添加TestNG依赖。你可以在Maven仓库中找到TestNG的依赖信息。 3. 创建一个测试类,并使用@Test注解标记测试方法。你可以在这些测试方法中编写你的测试代码。 4. 配置TestNG运行器。你可以在测试类上使用@Test注解的属性来配置TestNG的一些属性,比如并发模式、测试套件等。 5. 运行测试。你可以使用Maven命令或者集成开发环境中的TestNG插件来运行测试。 6. 查看测试报告。TestNG会生成详细的测试报告,包括测试结果、执行时间等信息。你可以在控制台输出查看,也可以保存为文件。 请注意,Spring Boot和TestNG的集成并没有一个固定的标准方法,具体的实现方式可能会因项目的不同而有所差异。你可以根据你的项目需求和喜好来选择适合的方法。 提到了导出报告的方法,你可以按照他的说明来导出测试报告。至于覆盖率报告,可以使用代码覆盖工具,比如JaCoCo来生成覆盖率报告。你可以配置JaCoCo插件来生成覆盖率报告,并将报告存放在项目的目录下。确保报告的存放路径与项目的层级结构一致,以便生成正确的覆盖率报告。 总结来说,你可以通过集成Spring Boot和TestNG来实现自动化测试。在项目中编写测试代码,并使用TestNG运行器来执行测试。使用TestNG生成详细的测试报告,并使用代码覆盖工具来生成覆盖率报告。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Leoon123

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值