简介

本篇文章我们将会探讨一下怎么在SpringBoot使用测试,Spring Boot有专门的spring-boot-starter-test,通过使用它可以很方便的在Spring Boot进行测试。

本文将从repository,service, controller,app四个层级来详细描述测试案例。

添加maven依赖

org.springframework.boot    spring-boot-starter-test    testcom.h2database    h2    test

我们添加spring-boot-starter-test和com.h2database总共两个依赖。H2数据库主要是为了测试方便。

Repository测试

本例中,我们使用JPA,首先创建Entity和Repository:

@Entity@Table(name = "person")public class Employee {    @Id    @GeneratedValue(strategy = GenerationType.AUTO)    private Long id;    @Size(min = 3, max = 20)    private String name;    // standard getters and setters, constructors}
@Repositorypublic interface EmployeeRepository extends JpaRepository {    public Employee findByName(String name);}

测试JPA,我们需要使用@DataJpaTest:

@RunWith(SpringRunner.class)@DataJpaTestpublic class EmployeeRepositoryIntegrationTest {    @Autowired    private TestEntityManager entityManager;    @Autowired    private EmployeeRepository employeeRepository;    // write test cases here}

@RunWith(SpringRunner.class) 是Junit和Spring Boot test联系的桥梁。

@DataJpaTest为persistence layer的测试提供了如下标准配置:

  • 配置H2作为内存数据库
  • 配置Hibernate, Spring Data, 和 DataSource
  • 实现@EntityScan
  • 开启SQL logging

下面是我们的测试代码:

@Testpublic void whenFindByName_thenReturnEmployee() {    // given    Employee alex = new Employee("alex");    entityManager.persist(alex);    entityManager.flush();    // when    Employee found = employeeRepository.findByName(alex.getName());    // then    assertThat(found.getName())      .isEqualTo(alex.getName());}

在测试中,我们使用了TestEntityManager。 TestEntityManager提供了一些通用的对Entity操作的方法。上面的例子中我们使用TestEntityManager向Employee插入了一条数据。

Service测试

在实际的应用程序中,Service通常要使用到Repository。但是在测试中我们可以Mock一个Repository,而不用使用真实的Repository。

先看一下Service:

@Servicepublic class EmployeeServiceImpl implements EmployeeService {    @Autowired    private EmployeeRepository employeeRepository;    @Override    public Employee getEmployeeByName(String name) {        return employeeRepository.findByName(name);    }}

我们再看一下怎么Mock Repository。

@RunWith(SpringRunner.class)public class EmployeeServiceImplIntegrationTest {    @TestConfiguration    static class EmployeeServiceImplTestContextConfiguration {        @Bean        public EmployeeService employeeService() {            return new EmployeeServiceImpl();        }    }    @Autowired    private EmployeeService employeeService;    @MockBean    private EmployeeRepository employeeRepository;    // write test cases here}

看下上面的例子,我们首先使用了@TestConfiguration专门用在测试中的配置信息,在@TestConfiguration中,我们实例化了一个EmployeeService Bean,然后在EmployeeServiceImplIntegrationTest自动注入。

我们还是用了@MockBean,用来Mock一个EmployeeRepository。

我们看下Mock的实现:

    @Before    public void setUp() {        Employee alex = new Employee("alex");        Mockito.when(employeeRepository.findByName(alex.getName()))                .thenReturn(alex);    }    @Test    public void whenValidName_thenEmployeeShouldBeFound() {        String name = "alex";        Employee found = employeeService.getEmployeeByName(name);        assertThat(found.getName())                .isEqualTo(name);    }

上面的代码中,我们使用Mockito来Mock要返回的数据,然后在接下来的测试中使用。

测试Controller

和测试Service一样,Controller使用到了Service:

@RestController@RequestMapping("/api")public class EmployeeRestController {    @Autowired    private EmployeeService employeeService;    @GetMapping("/employees")    public List getAllEmployees() {        return employeeService.getAllEmployees();    }}

但是在测试的时候,我们并不需要使用真实的Service,我们需要Mock它 。

@RunWith(SpringRunner.class)@WebMvcTest(EmployeeRestController.class)public class EmployeeControllerIntegrationTest {    @Autowired    private MockMvc mvc;    @MockBean    private EmployeeService service;    // write test cases here

为了测试Controller,我们需要使用到@WebMvcTest,他会为Spring MVC 自动配置所需的组件。

通常情况下@WebMvcTest 会和@MockBean一起使用来提供Mock的具体实现。

@WebMvcTest也提供了自动配置的MockMvc,它为测试MVC Controller提供了更加简单的方式,而不需要启动完整的HTTP server。

@Testpublic void givenEmployees_whenGetEmployees_thenReturnJsonArray()  throws Exception {    Employee alex = new Employee("alex");    List allEmployees = Arrays.asList(alex);    given(service.getAllEmployees()).willReturn(allEmployees);    mvc.perform(get("/api/employees")      .contentType(MediaType.APPLICATION_JSON))      .andExpect(status().isOk())      .andExpect(jsonPath("$", hasSize(1)))      .andExpect(jsonPath("$[0].name", is(alex.getName())));}

given(service.getAllEmployees()).willReturn(allEmployees); 这一行代码提供了mock的输出。方面后面的测试使用。

@SpringBootTest的集成测试

上面我们讲的都是单元测试,这一节我们讲一下集成测试。

@RunWith(SpringRunner.class)@SpringBootTest(        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,        classes = TestApplication.class)@AutoConfigureMockMvc@TestPropertySource(        locations = "classpath:application-integrationtest.properties")public class EmployeeAppIntegrationTest {    @Autowired    private MockMvc mvc;    @Autowired    private EmployeeRepository repository;}

集成测试需要使用@SpringBootTest,在@SpringBootTest中可以配置webEnvironment,同时如果我们需要自定义测试属性文件可以使用@TestPropertySource。

下面是具体的测试代码:

   @After    public void resetDb() {        repository.deleteAll();    }    @Test    public void givenEmployees_whenGetEmployees_thenStatus200() throws Exception {        createTestEmployee("bob");        createTestEmployee("alex");        // @formatter:off        mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON))                .andDo(print())                .andExpect(status().isOk())                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))                .andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2))))                .andExpect(jsonPath("$[0].name", is("bob")))                .andExpect(jsonPath("$[1].name", is("alex")));        // @formatter:on    }    //    private void createTestEmployee(String name) {        Employee emp = new Employee(name);        repository.saveAndFlush(emp);    }

欢迎关注我的公众号:程序那些事,更多精彩等着您!

更多内容请访问:flydean的博客 flydean.com

jpa怎么传参到in中_Spring Boot中的测试相关推荐

  1. jfinal ajax传值,JFINAL+Ajax传参 array 数组方法 获取request中数组操作

    前台代码js var _list =[]; for (var i = 0; i < array.length; i++) { _list[i] = array[i]; } $.ajax({ ty ...

  2. jpa oracle 传参int类型判空_企业级Java开发之图解JPA核心构件

    编者按: 企业级的软件开发中,Java一直都是中流砥柱.在Java EE8之后,Oracle公司把企业级Java标准控制权转交Eclipse基金.最新或·和以后的企业级Java将冠名为Jakarta ...

  3. java restful接口开发实例_Spring Boot 中 10 行代码构建 RESTful 风格应用!

    点击上方"Java后端技术",选择"置顶或者星标" 你关注的就是我关心的! 作者:江南一点雨 微信公众号:牧码小子(ID:a_javaboy) 推荐阅读:10个 ...

  4. 全志H3 uboot传参到内核分析,boot.scr文件分析

    传参过程 uboot倒计时结束,默认以bootcmd来启动内核,它等于 fatload mmc 0:1 ${scriptaddr} boot.scr; source ${scriptaddr} 上面两 ...

  5. restful接口开发实例_Spring Boot 中 10 行代码构建 RESTful 风格应用

    松哥原创的四套视频教程已经全部杀青,感兴趣的小伙伴戳这里-->Spring Boot+Vue+微人事视频教程 RESTful ,到现在相信已经没人不知道这个东西了吧!关于 RESTful 的概念 ...

  6. ckeditor回显带标签_Spring Boot中带有CKEditor的AJAX

    ckeditor回显带标签 1.概述 在本文中,我们将介绍如何在Spring Boot中使用CKEditor . 在本教程中,我们将导入一个包含大量数据的XML文档,对使用GET请求将一组数据加载到C ...

  7. BCrypt加密怎么存入数据库_Spring Boot 中密码加密的两种姿势

    1.为什么要加密 2.加密方案 3.实践3.1 codec 加密3.2 BCryptPasswordEncoder 加密 4.源码浅析 先说一句:密码是无法解密的.大家也不要再问松哥微人事项目中的密码 ...

  8. springboot事务回滚源码_Spring Boot中的事务是如何实现的

    1. 概述 一直在用SpringBoot中的@Transactional来做事务管理,但是很少想过SpringBoot是如何实现事务管理的,今天从源码入手,看看@Transactional是如何实现事 ...

  9. eclipse中tomcat启动不了_Spring Boot中Tomcat是怎么启动的

    Spring Boot一个非常突出的优点就是不需要我们额外再部署Servlet容器,它内置了多种容器的支持.我们可以通过配置来指定我们需要的容器. 本文以我们平时最常使用的容器Tomcat为列来介绍以 ...

最新文章

  1. Linux内核2.6的进程调度
  2. python3爬虫入门教程-Python3爬虫学习入门教程
  3. 这便是有三AI一年的底蕴,那些5000粉丝1000阅读量的AI技术干货
  4. 海贼王热血航线正在连接服务器,航海王热血航线连接服务器失败?解决方法一览...
  5. php计算时间顺延3分,PHP关于strtotime函数的大坑
  6. ssm(Spring、Springmvc、Mybatis)实战之淘淘商城-第七天(非原创)
  7. 如何使用 一行代码 搞定一组数据的(极值、平均值、中位数、四分位数、数量统计和标准差)
  8. 网络爬虫--8.编码趣闻
  9. springmvc的ModelAttribute注解
  10. centos识别移动硬盘U盘,需安装【ntfs-3g】
  11. 防SQL注入(转载)
  12. The block problem poj1208
  13. Python 字典(Dictionary) 基本操作
  14. 抽象代数 01.06 变换群与置换群
  15. win10专业版虚拟机配置服务器,win10专业版怎么运行虚拟机_win10专业版开启虚拟机的方法...
  16. 2016英语三级分数计算机,公共英语三级考试分数权重计算方法
  17. win10如何离线安装.NET Framework3.5
  18. 从无到有完整搭建lnmp+redis+memcache+gearmand网站
  19. 成功解决 word2019设置背景色为护眼的绿色
  20. 流量都去哪儿了——三板斧搞定Android网络流量测试

热门文章

  1. 皮一皮:手机?橡皮?傻傻分不清...
  2. ES 的分布式架构原理能说一下么?
  3. 唠唠面试常问的:面向对象六大原则
  4. activemq broker集群_17 个方面,综合对比 Kafka、RabbitMQ、RocketMQ、ActiveMQ
  5. 【SpringCloud】Feigin:伪装
  6. Oracle经验集锦
  7. 微信小程序开发者工具升级自动预览功能,福利啊
  8. torch 归一化,momentum用法详解
  9. libtorch demo
  10. torch max 判断与筛选