1

使用Kotlin (Spring Boot) + MockMVC + DatabaseRider轻松实现API集成测试

 1 year ago
source link: https://www.jdon.com/63263
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

使用Kotlin (Spring Boot) + MockMVC + DatabaseRider轻松实现API集成测试


在本文中,我将介绍如何对使用服务器端 Kotlin(Spring Boot)创建的 Web API 进行 API 集成测试。通过结合MockMVC和DatabseRider,可以轻松实现API集成测试。

MockMVC
MockMVC 是 Spring Test 中包含的测试框架之一。无需手动向实现的服务器发送请求即可进行 API 测试。
MockMVC 需要 @AutoConfigureMockMvc 和 @SpringBootTest 进行初始化。

class SampleTest {
    @SpringBootTest
    @AutoConfigureMockMvc
    @TestInstance(TestInstance.Lifecycle.PER_CLASS)
    class Get {
        @Autowired
        lateinit var mockMvc: MockMvc

        @BeforeAll
        fun reset() = //每次测试时执行的操作


        @Test
        fun test() {

        }
    }
}

使用 MockMvc 发送请求参数如下。还可以评估响应状态和响应正文。

val response = mockMvc.perform(
    MockMvcRequestBuilders
        .get("/path/to/api")
        .contentType(MediaType.APPLICATION_JSON)
).andReturn().response
val actualStatus = response.status
val actualResponseBody = response.contentAsString

DatabaseRider
DatabaseRider 是一个 Java 库,它允许您使用注释简洁地编写 DB 测试。如下图,注解可以让你插入输入数据,测试后期待DB,测试完成后将表写入文件。这意味着您可以在测试之前指定要插入数据库的数据,并在测试之后比较数据库应该是什么。E2E API测试除了能保证响应外,还能保证DB状态,与API测试非常兼容。

@Test
@DBRider
@DataSet("path/to/input/data.{yml,csv,cml}")// 指定输入数据文件
@ExpectedDataSet(
    value = ["path/to/expected/data.{yml,csv,cml}"], //指定预期数据的文件
    orderBy = ["id"]。
    ignoreCols = ["createdAt", "upedAt"], // 忽略元数据
)
// 注意:一旦数据被导出,注释掉
@ExportDataSet(
    format = DataSetFormat.YML, // 指定测试完成后数据导出的格式。
    outputName = "path/to/export/data.{yml,csv,cml}", // 指定要导出的文件。
    includeTables = ["customer"] // 指定要包括的列
)
fun `test`() {
    // 编写测试。
}

更多见:Github


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK