额外
模拟查询

模拟

自 v0.6.4 起可用

在为使用 Prisma 客户端的函数编写测试时,可能难以运行真实的数据库进行测试。为了解决这个问题,您可以在 prisma-client-rustprisma-client-rust-cli 上启用 mocking 功能,并创建一个“模拟”客户端,使用您预先提供的数据运行查询。这允许您定义查询的预期结果,然后使用这些预期结果执行测试。

示例使用以下 Prisma 模式

model Post {
    id    String   @default(cuid()) @id
    title String
}

假设您有一个函数 get_post_title

use prisma::{PrismaClient, post};
use prisma_client_rust::queries;
 
async fn get_post_title(
    client: &PrismaClient,
    post_id: String,
) -> queries::Result<Option<String>> {
    let post = client.post().find_unique(post::id::equals(post_id)).await?;
 
    post.map(|post| post.title)
}

要编写单元测试,首先使用 PrismaClient::_mock 创建一个模拟客户端和模拟存储,通过模拟存储定义您的期望,然后运行测试。模拟客户端将使用模拟存储中的数据来解析查询。

#[cfg(test)]
mod test {
	use super::*;
 
	#[tokio::test]
	async fn gets_title() -> queries::Result<()> {
		let (client, mock) = PrismaClient::_mock().await;
 
		let id = "123".to_string();
		let expected_title = "Test".to_string();
 
		mock.expect(
			// First argument is query without calling 'exec'
			client.post().find_unique(post::id::equals(post_id)),
			// Second argument is expected return type.
			// This will fail to compile if it does not match
			// the return type of the query
			post::Data {
				id: id.clone(),
				title: expected_title.to_string(),
			},
		)
		.await;
 
		 let title = get_post_title(&client, id).await?;
 
		 assert_eq!(title, Some(expected_title));
	}
}