后端开发:集成测试、零停机部署与邮件确认功能实现
1. 构建 API 客户端
在进行集成测试时,我们采用黑盒测试的方式,在每个测试开始时启动应用程序,并使用 HTTP 客户端(如 reqwest )与之交互。在编写测试的过程中,我们不可避免地要为 API 实现一个客户端,这让我们能以用户的视角体验与 API 的交互。但要注意,不能让客户端逻辑在测试套件中分散,否则当 API 发生变化时,修改会变得非常麻烦。
以订阅测试为例,我们发现每个测试中都有相同的调用代码,因此可以将其提取出来,为 TestApp 结构体添加一个辅助方法:
// tests/api/helpers.rs
pub struct TestApp {
// ...
}
impl TestApp {
pub async fn post_subscriptions(&self, body: String) {
reqwest::Client::new()
.post(&format!("{}/subscriptions", &self.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
.await
.expect("Failed to execute request.")
}
}
超级会员免费看
订阅专栏 解锁全文
2123

被折叠的 条评论
为什么被折叠?



