内容简介:事实上springboot框架是一个tdd框架,你在进行建立项目时它会同时建立一个单元测试项目,而我们的代码用例可以在这个项目里完成,对于单元测试大叔有以下几点需要说明一下:下面直接写单元测试即可,业务层不用修改,数据库根据对于h2在单元测试里的使用就说这么说,有不清楚的可以给大叔留言!
单元测试有几点要说的
事实上springboot框架是一个tdd框架,你在进行建立项目时它会同时建立一个单元测试项目,而我们的代码用例可以在这个项目里完成,对于单元测试大叔有以下几点需要说明一下:
- 单元测试的用例之间不要有相互依赖
- 单元测试数据来源为本地,不要访问外部资源,外部数据库也是不行的
- 对于集成测试,每个控制器对应一个测试类,它们可以有统一的抽象基类,用来存储公用的属性,如数据对象,http对象等
引入相关依赖包
testCompile('com.h2database:h2')
下面对h2数据库的配置
spring:
profiles: integTest
cloud.config.enabled: false
h2:
console:
enabled: true
path: /h2
datasource:
url: jdbc:h2:mem:testdb;MODE=MYSQL;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false
driver-class-name: org.h2.Driver
username: sa
password: sa
schema-username: sa
schema-password: sa
data-username: sa
data-password: sa
schema: classpath:db/*.sql
data: classpath:data/*.sql
initialization-mode: always
platform: h2
下面直接写单元测试即可,业务层不用修改,数据库根据 profile
去选择 mysql 还是h2
@RunWith(SpringRunner.class)
@ActiveProfiles("integTest")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class ControllerTestBase {
protected MockMvc mockMvc;
@Autowired
protected ObjectMapper objectMapper;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
public class CustomerTagsControllerTest extends ControllerTestBase {
@Autowired
CustomerTagsService customerTagsService;
@Test
public void getCustomerTags() throws Exception {
mockMvc.perform(
get("/api/tags")
.accept(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].tagsDescription").value("未接"));
}
}
对于h2在单元测试里的使用就说这么说,有不清楚的可以给大叔留言!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Java 与'嵌入式' PostgreSQL 数据库的单元测试
- springboot~Profile开发环境与单元测试用不同的数据库
- javascript – 如何针对Knex进行单元测试时,如何模拟假数据库?
- 学习 Node.js,第 9 单元:单元测试
- Vue 应用单元测试的策略与实践 02 - 单元测试基础
- Vue 应用单元测试的策略与实践 04 - Vuex 单元测试
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Building Websites with Joomla!
H Graf / Packt Publishing / 2006-01-20 / USD 44.99
This book is a fast paced tutorial to creating a website using Joomla!. If you've never used Joomla!, or even any web content management system before, then this book will walk you through each step i......一起来看看 《Building Websites with Joomla!》 这本书的介绍吧!