集成测试还是单元测试:FastAPI 项目里的真实取舍(续)
发送邮件、发短信、调用支付接口、推送通知——这些在测试里触发了就是真的触发了。mock 是唯一合理的选择,测试要验证的是"发送行为有没有被正确调用",而不是"邮件真的发出去没有":
async def test_register_sends_welcome_email(client: AsyncClient):
sent_emails = []
async def mock_send_email(to: str, subject: str, body: str):
sent_emails.append({"to": to, "subject": subject})
with patch("app.services.email.send", side_effect=mock_send_email):
await client.post("/users/register", json={
"email": "new@example.com",
"password": "pass123",
})
assert len(sent_emails) == 1
assert sent_emails[0]["to"] == "new@example.com"
情况二:非确定性的值,测试里需要被控制
datetime.now()、uuid.uuid4()、随机数——这类依赖每次调用结果不同,测试无法写出确定的断言。mock 是为了让测试结果可预测: