Use h2 database for unit testing

Simply using Mockito to simulate the interface to return data cannot meet our needs for testing complex SQL.

Therefore, it is a good choice to use the h2 database for unit testing .

The code structure is as follows:

src/test/java
    --Test.java
src/test/resources
    --application.yml        ->根据就近原则,执行测试用例时,会使用test中的这个配置文件
    --schema.sql             ->h2数据库建表语句脚本
src/test/resources/sql
    --table1_init_data.sql
    --table2_init_data.sql   ->表初始化数据

yml configuration:

spring:
  datasource:
    url: "jdbc:h2:mem:test_db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=TRUE;MODE=MSSQLServer;USER=sa;PASSWORD=0000abc"
    driver-class-name: org.h2.Driver
    username: sa
    password: 0000abc
    schema: classpath:schema.sql     #执行建表语句
    data: classpath:sql/*.sql        #执行数据初始化

Test case:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class Test {
    @Autowired
    MockMvc mockMvc;
    @Test
    public void test01(){     mockMvc.perform(post("/XXX").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON)
                .content(requsetJson.getBytes()))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(content().json(new JSONObject()
                        .put("code", "200")
                        .put("message", "success").toString()))
                .andDo(print()); //输出MvcResult到控制台
    }
}

In this way, the entire code flow can be tested. If some tests need to use special data, you can specify sql to initialize the data:

    @Test
    @Sql(value = {
            "/truncate_all.sql", // truncate脚本
            "/sql/xxx.sql", //数据初始化脚本
            "/sql/xxx.sql"
    })

Guess you like

Origin blog.csdn.net/kaiyuantao/article/details/120269575