spring boot單元測試之五:用mybatis+H2數據庫測試sql(spring boot 2.4.3)


一,關於H2數據庫:

   1,H2數據庫的用途:
      H2是一個用Java開發的嵌入式數據庫,可以直接嵌入到應用項目中。
  H2可以用於單元測試。它啟動速度很快,而且可以關閉持久化功能,使每一個用例執行完后就還原到初始狀態。

2,官方網站:

http://www.h2database.com/html/main.html

說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest

         對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/

說明:作者:劉宏締 郵箱: 371125307@qq.com

 

二,演示項目的相關信息

1,地址:

https://github.com/liuhongdi/h2test

2,功能:演示集成h2數據庫用來做單元測試中對sql的測試:

3,項目結構:如圖:

 

 

 

 

三,配置文件說明

1,pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--mybatis begin-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <!--mybatis end-->

        <!--mysql begin-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--mysql end-->

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>1.4.200</scope>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

2,application.yml

spring:
  profiles:
    active: dev

3,application-prd.yml

#error
server:
  error:
    include-stacktrace: always
#errorlog
logging:
  level:
    org.springframework.web: trace
#mysql
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/store?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: lhddemo
    driver-class-name: com.mysql.cj.jdbc.Driver
    maximum-pool-size: 12
    minimum-idle: 10
    idle-timeout: 500000
    max-lifetime: 540000

#mybatis
mybatis:
  mapper-locations: classpath:/mapper/*Mapper.xml
  type-aliases-package: com.example.demo.mapper
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

 

4,application-dev.yml

#error
server:
  error:
    include-stacktrace: always
#errorlog
logging:
  level:
    org.springframework.web: trace
#mysql
spring:
  h2:
    console:
      path: /h2-console #進入h2 web操作界面的路徑
      enabled: true #開啟h2 web界面
  datasource:
    driver-class-name: org.h2.Driver
    schema: classpath:db/schema-h2.sql
    data: classpath:db/data-h2.sql
    url: jdbc:h2:mem:test
    username: root
    password: test
#mybatis
mybatis:
  mapper-locations: classpath:/mapper/*Mapper.xml
  type-aliases-package: com.example.demo.mapper
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

 

5,db/schema-h2.sql

DROP TABLE IF EXISTS goods;

CREATE TABLE goods (
 goodsId BIGINT(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
 goodsName varchar(500)  NOT NULL DEFAULT '' COMMENT 'name',
 subject varchar(200) NOT NULL DEFAULT '' COMMENT '標題',
 price decimal(15,2) NOT NULL DEFAULT '0.00' COMMENT '價格',
 stock int(11) NOT NULL DEFAULT '0' COMMENT 'stock',
 PRIMARY KEY (`goodsId`),
 UNIQUE KEY `goodsName` (`goodsName`)
)

 

6,db/data-h2.sql

INSERT INTO `goods` (`goodsId`, `goodsName`, `subject`, `price`, `stock`) VALUES
(3, '100分電動牙刷', '好用到讓你愛上刷牙', '59.00', 98),
(4, '蜂蜜牛奶手工皂', '深入滋養,肌膚細膩嫩滑', '70.00', 33),
(5, '紫光筷子筒', '紫光智護,干爽防潮更健康', '189.00', 20),
(6, '野性mini便攜式藍牙音箱', '強悍機能,品味豪邁', '499.00', 3),
(7, '樂穿梭茶具', '茶具+茶葉精美端午禮盒', '299.00', 8),
(8, '香梅 昂 吟釀清酒', '入口清爽,回甘無窮', '260.00', 3),
(9, '小風扇落地電扇', '四檔風速調節,低噪音運行', '239.00', 6),
(10, '梵高系列20英寸拉桿箱', '梵高名畫復原,旅行的藝術', '799.00', 4),
(11, '英國老牌城市系列劍橋包', '源自英倫 從經典到潮流', '1210.00', 9),
(12, '正宗無錫陽山水蜜桃', '手捏可以榨汁', '78.00', 100),
(13, '懸浮歌詞透明藍牙音箱1 in h2', '極簡主義美學 HiFi音質 h2', '3499.00', 60);

 

四,java代碼說明

1,result/RestResult.java

public class RestResult implements Serializable {

    //uuid,用作唯一標識符,供序列化和反序列化時檢測是否一致
    private static final long serialVersionUID = 7498483649536881777L;
    //標識代碼,0表示成功,非0表示出錯
    private Integer code;
    //提示信息,通常供報錯時使用
    private String msg;
    //正常返回時返回的數據
    private Object data;

    public RestResult(Integer status, String msg, Object data) {
        this.code = status;
        this.msg = msg;
        this.data = data;
    }

    //返回成功數據
    public static RestResult success(Object data) {
        return new RestResult(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg(), data);
    }

    public static RestResult success(Integer code,String msg) {
        return new RestResult(code, msg, null);
    }

    //返回出錯數據
    public static RestResult error(ResponseCode code) {
        return new RestResult(code.getCode(), code.getMsg(), null);
    }
    public static RestResult error(Integer code,String msg) {
        return new RestResult(code, msg, null);
    }

    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }

}

 

2,service/GoodsService.java

@Service
public class GoodsService {
    @Resource
    private GoodsMapper goodsMapper;

    //得到一件商品的信息
    public Goods getOneGoodsById(Long goodsId) {
        System.out.println("get data from mysql");
        Goods goodsOne = goodsMapper.selectOneGoods(goodsId);
        System.out.println(goodsOne);
        return goodsOne;
    }

    //添加一件商品到數據庫
    public Long addOneGoods(Goods goods) {
        int insNum = goodsMapper.insertOneGoods(goods);
        if (insNum == 0) {
            return 0L;
        } else {
            Long goodsId = goods.getGoodsId();//該對象的自增ID
            return goodsId;
        }
    }
}

 

3,pojo/Goods.java

public class Goods {
    //商品id
    Long goodsId;
    public Long getGoodsId() {
        return this.goodsId;
    }
    public void setGoodsId(Long goodsId) {
        this.goodsId = goodsId;
    }

    //商品名稱
    private String goodsName;
    public String getGoodsName() {
        return this.goodsName;
    }
    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }

    //商品標題
    private String subject;
    public String getSubject() {
        return this.subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }

    //商品價格
    private BigDecimal price;
    public BigDecimal getPrice() {
        return this.price;
    }
    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    //庫存
    int stock;
    public int getStock() {
        return this.stock;
    }
    public void setStock(int stock) {
        this.stock = stock;
    }

    @Override
    public String toString(){
        return " Goods:goodsId=" + goodsId +" goodsName=" + goodsName+" subject=" + subject+" price=" + price+" stock=" + stock;
    }
}

 

4,mapper/GoodsMapper.java

@Repository
@Mapper
public interface GoodsMapper {
    Goods selectOneGoods(Long goodsId);
    int insertOneGoods(Goods goods);
    int updateOneGoods(Goods goods);
}

 

5,mapper/GoodsMapper.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.h2test.demo.mapper.GoodsMapper">

    <select id="selectOneGoods" parameterType="long" resultType="com.h2test.demo.pojo.Goods">
        select * from goods where goodsId=#{goodsId}
    </select>

    <update id="updateGoodsStock">
        UPDATE goods SET
        stock = stock+#{changeAmount,jdbcType=INTEGER}
        WHERE goodsId = #{goodsId,jdbcType=BIGINT}
    </update>

    <insert id="insertOneGoods" parameterType="com.h2test.demo.pojo.Goods" useGeneratedKeys="true" keyProperty="goodsId" >
        insert into goods(goodsName,subject,price,stock)
        values(
            #{goodsName},#{subject},#{price},#{stock}
        )
     </insert>

</mapper>

 

6,service/GoodsServiceTest.java

@ActiveProfiles("dev")
@SpringBootTest
class GoodsServiceTest {

    @Autowired
    GoodsService goodsService;

    @Test
    @DisplayName("商品service:得到一件商品")
    void getOneGoodsById() {
        Goods goodsRet = goodsService.getOneGoodsById(13L);
        assertThat(goodsRet.getGoodsId(), equalTo(13L));
    }

    @Test
    @DisplayName("商品service:測試添加一件商品")
    void addOneGoods() {
        Goods goodsOne = new Goods();
        //goodsOne.setGoodsId(13L);
        goodsOne.setGoodsName("商品名稱");
        goodsOne.setSubject("商品描述");
        goodsOne.setPrice(new BigDecimal(101));
        goodsOne.setStock(13);

        Long goodsId = goodsService.addOneGoods(goodsOne);
        assertThat(goodsId, equalTo(14L));

        Goods goodsRet = goodsService.getOneGoodsById(14L);
        assertThat(goodsRet.getGoodsId(), equalTo(14L));
    }
}

 

五,測試效果

1,執行測試:

 

 

2,訪問h2的控制台:

地址:

http://127.0.0.1:8080/h2-console

登錄:

返回:

 

 

六,查看spring boot版本:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.3)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM