使用h2数据库单元测试

1 篇文章 0 订阅

SpringBoot使用h2数据库单元测试


SpringBoot项目在做单元测试时,若直接对业务数据库进行操作,会扰乱测试数据,所以我们在实际业务开发时,会选择h2作为单元测试的数据库。
H2数据库是一个开源的关系型数据库。H2是一个嵌入式数据库引擎,采用java语言编写,不受平台的限制,同时支持网络版和嵌入式版本,有比较好的兼容性,支持相当标准的sql标准,支持集群。下面我们来学习下如何在项目中使用h2做单元测试。

  1. h2数据库配置:

spring:
  datasource:
    driver-class-name: org.h2.Driver
    username: sa
    password:
    url: jdbc:h2:mem:h2test;DB_CLOSE_DELAY=-1
    schema: classpath:scheme.sql
    data: classpath:data.sql
  jpa:
    hibernate:
      ddl-auto: none
    show-sql: true
    generate-ddl: false
logging:
  level:
    root: info

resources目录放入scheme.sql(表结构)、data.sql(表数据)文件:

scheme.sql:

create table if not exists users (id int not null primary key auto_increment,username varchar(100),password varchar(100),status int);

data.sql:

insert into users(id, username, password, status) VALUES (1,'test','123456',1);

在这里插入图片描述

2.实体类、dao、controller层及异常处理:


@Entity
@Data
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column
    private String username;

    @Column
    private String password;

    @Column
    private int status;
}

public interface UserRepository extends JpaRepository<User, Long> {
}
 /**
     * 查询用户信息
     *
     * @param id
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/user/{id}")
    public ResponseEntity findById(@PathVariable Long id) throws Exception {

        Optional optional = this.userRepository.findById(id);
        if (!optional.isPresent()) {
            throw new Exception("user not exists");
        }
        User user = (User) optional.get();
        return ResponseEntity.status(HttpStatus.OK).body(user);
    }
@ControllerAdvice
public class ExceptionHandlers {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handle(Exception e) {
        return e.getMessage();
    }
}

3.单元测试:


@SpringBootTest
@RunWith(SpringRunner.class)
public class H2testApplicationTests {

    @Autowired
    private WebApplicationContext webApplicationContext;

    protected MockMvc mvc;

    @Before
    public void setUp() {
        mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void test1() throws Exception{
        MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get("/user/1"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
        JSONObject object = JSONObject.parseObject(mvcResult.getResponse().getContentAsString());
        Assert.assertEquals("成功的测试用例", 4, object.size());
    }


}

4.demo github地址:链接: link.

欢迎关注博主个人公众号:java行进者
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值