集成测试还是单元测试:FastAPI 项目里的真实取舍(续)
async def publish_post(post_id: int, user_id: int, db: AsyncSession) -> Post:
post = await db.get(Post, post_id)
if not post:
raise HTTPException(status_code=404)
if post.author_id != user_id:
raise HTTPException(status_code=403)
if post.status == "archived":
raise PostArchivedError()
if post.word_count < 100:
raise PostTooShortError()
post.status = "published"
post.published_at = datetime.now()
await db.commit()
return post
这个函数里有三类东西混在一起:数据库读写、权限校验、业务规则(归档判断、字数判断)。
如果你想对"归档文章不能发布"和"字数不足不能发布"这两条业务规则写单元测试,只能 mock 掉数据库——这就变成了成本高但价值低的 mock 测试。
更合理的做法是把纯业务规则提取出来: