单元测试与springcloud

spring,spring boot,spring cloud版本

<!-- 注意: spring,spring boot,spring cloud三者的版本需要配套 -->
<spring.version>5.0.12.RELEASE</spring.version>
<spring-boot.version>2.0.8.RELEASE</spring-boot.version>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
<oracle.jdbc.version>11.2.0.4</oracle.jdbc.version>
<mysql.jdbc.version>5.1.47</mysql.jdbc.version>
<pagehelper-spring-boot-starter.version>1.2.5</pagehelper-spring-boot-starter.version>

yml配置(内存数据库)

spring:
profiles:
active: dev
 # springcloud兼容h2
cloud:
refresh:
refreshable: none
datasource:
username:
password:
url: jdbc:h2:mem:test
schema: classpath*:sql/001_ddl.sql
data:
- classpath*:sql/002_sample.sql # 简单的示例
- classpath*:sql/003_resource_service.sql
driver-class-name: org.h2.Driver
initialization-mode: always

PostConstruct与PreDestroy

@PostConstruct
被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。
@PreDestroy
  被@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。

单元测试

unit test和集成测试,两个用的stub是分开的

  • rest服务单元测试
    @AutoConfigureMockMvc 针对Test类的注解

  • 类中注入MockMvc
    @Autowired
    protected MockMvc mvc;

  • 模拟http
    //test下的resources目录下的stub目录下json文件
    @Rule
    public MocoJunitRunner baseRunner = jsonHttpRunner(端口, pathResource("stub/XXX.json"));

  • 发送请求//单元测试中in为入参报文 out为出参报文
    RequestBuilder request = post("请求url").content(in);
    mvc.perform(request).andExpect(status().isOk()).andExpect(content().json(out));

猜你喜欢

转载自www.cnblogs.com/lyx-me/p/10486096.html