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