springboot 测试用例 gradle

发布时间 2023-06-13 11:51:54作者: vx_guanchaoguo0

在springboot 2.4.5之后的 变成了jinut5

  • 直接引用即可 不需要排除 org.junit.jupiter.api.Test
org.springframework.boot:spring-boot-starter-test

测试数据 H2

package com.example.test_pro_gradle;


import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

import java.util.Optional;

@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class TestProGradleApplicationTest {
    
    @Autowired
    ProductCategoryRepository repository;
    private final Logger logger = LoggerFactory.getLogger(TestProGradleApplicationTest.class);

    @Test
    public void test1() {
        // 打印版单测
        System.out.println("=========");
        logger.info("info...");
    }

    @Test
    public void testFindById() {
        Optional<ProductCategory> byId = repository.findById(1);
        System.out.println("查询结果:");
        System.out.println(byId);
    }
  
}

数据实体

package com.example.test_pro_gradle;

import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;

@Data
@Entity
public class ProductCategory implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "id", nullable = false)
    private Integer id;
}

仓库接口

package com.example.test_pro_gradle;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductCategoryRepository extends JpaRepository<ProductCategory, Integer> {
}

数据源 使用内存数据库

spring:
  jpa:
    show-sql: true
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:testdb
    username: root
    password: root