事实上springboot框架是一个tdd框架,你在进行建立项目时它会同时建立一个单元测试项目,而我们的代码用例可以在这个项目里完成,对于单元测试大叔有以下几点需要说明一下:
testCompile('com.h2database: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在单元测试里的使用就说这么说,有不清楚的可以给大叔留言!