使用模拟客户端编写测试

借助 Rust 版 Cloud 客户端库,您可以对实际客户端实现进行桩处理,并注入模拟进行单元测试。使用模拟客户端,您可以编写受控、可靠的单元测试,而无需进行网络调用或产生费用。

准备工作

在运行本文档中的代码之前,请按照开始使用 Rust 中的说明安装 Rust 并设置 Cargo 项目。

依赖项

本文档使用 mockall crate 作为其模拟框架,并使用 Speech-to-Text 中的 Speech 客户端来说明工作流。其他生成的客户端也采用相同的模式。

将客户端库和 google-cloud-gax 添加到 Cargo.toml 文件中:

cargo add google-cloud-speech-v2 google-cloud-gax

将 mockall 和 tokio 添加为开发依赖项:

cargo add --dev mockall
cargo add --dev tokio --features macros,rt-multi-thread

模拟客户端

如需在不进行网络调用的情况下测试代码,请在模拟结构体上实现服务的桩特征,并配置其预期。然后,使用 from_stub 构建客户端,并将其传递给应用函数:

  1. 添加 use 别名以缩短 crate 名称:

    use google_cloud_gax as gax;
    use google_cloud_speech_v2 as speech;

  2. 编写一个应用函数,该函数接受对 Speech 客户端的引用,调用 get_recognizer,并处理服务器响应:

    // An example application function.
    //
    // It makes an RPC, setting some field. In this case, it is the `GetRecognizer`
    // RPC, setting the name field.
    //
    // It processes the response from the server. In this case, it extracts the
    // display name of the recognizer.
    async fn my_application_function(client: &speech::client::Speech) -> gax::Result<String> {
        client
            .get_recognizer()
            .set_name("invalid-test-recognizer")
            .send()
            .await
            .map(|r| r.display_name)
    }

  3. 定义一个使用 mockall::mock! 实现 speech::stub::Speech 特征的模拟结构体:

    mockall::mock! {
        #[derive(Debug)]
        Speech {}
        impl speech::stub::Speech for Speech {
            async fn get_recognizer(&self, req: speech::model::GetRecognizerRequest, _options: gax::options::RequestOptions) -> gax::Result<gax::response::Response<speech::model::Recognizer>>;
        }
    }

  4. 在测试中,创建模拟实例。mockall::mock! 宏会将 Mock 附加到结构体名称前面,以创建 MockSpeech:

    let mut mock = MockSpeech::new();

  5. 在模拟上配置预期,以验证传入的请求字段并返回模拟的 Recognizer 响应:

    mock.expect_get_recognizer()
        .withf(move |r, _|
            // Optionally, verify fields in the request.
            r.name == "invalid-test-recognizer")
        .return_once(|_, _| {
            Ok(gax::response::Response::from(
                speech::model::Recognizer::new().set_display_name("test-display-name"),
            ))
        });

  6. 使用 Speech::from_stub 根据模拟对象构建 Speech 客户端:

    let client = speech::client::Speech::from_stub(mock);

  7. 使用模拟客户端调用应用函数:

    let display_name = my_application_function(&client).await?;

  8. 验证返回值:

    assert_eq!(display_name, "test-display-name");

模拟错误

如需测试错误处理,请将模拟预期配置为返回使用 Error::service 构建的 Err:

mock.expect_get_recognizer().return_once(|_, _| {
    // This time, return an error.
    use gax::error::Error;
    use gax::error::rpc::{Code, Status};
    let status = Status::default()
        .set_code(Code::NotFound)
        .set_message("Resource not found");
    Err(Error::service(status))
});

完整代码

以下示例将成功和错误单元测试合并到一个完整的测试模块中:

#[cfg(test)]
mod tests {
    use google_cloud_gax as gax;
    use google_cloud_speech_v2 as speech;
    type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

    // An example application function.
    //
    // It makes an RPC, setting some field. In this case, it is the `GetRecognizer`
    // RPC, setting the name field.
    //
    // It processes the response from the server. In this case, it extracts the
    // display name of the recognizer.
    async fn my_application_function(client: &speech::client::Speech) -> gax::Result<String> {
        client
            .get_recognizer()
            .set_name("invalid-test-recognizer")
            .send()
            .await
            .map(|r| r.display_name)
    }

    mockall::mock! {
        #[derive(Debug)]
        Speech {}
        impl speech::stub::Speech for Speech {
            async fn get_recognizer(&self, req: speech::model::GetRecognizerRequest, _options: gax::options::RequestOptions) -> gax::Result<gax::response::Response<speech::model::Recognizer>>;
        }
    }

    #[tokio::test]
    async fn basic_success() -> Result<()> {
        // Create a mock, and set expectations on it.
        let mut mock = MockSpeech::new();
        mock.expect_get_recognizer()
            .withf(move |r, _|
                // Optionally, verify fields in the request.
                r.name == "invalid-test-recognizer")
            .return_once(|_, _| {
                Ok(gax::response::Response::from(
                    speech::model::Recognizer::new().set_display_name("test-display-name"),
                ))
            });

        // Create a client, implemented by the mock.
        let client = speech::client::Speech::from_stub(mock);

        // Call our function.
        let display_name = my_application_function(&client).await?;

        // Verify the final result of the RPC.
        assert_eq!(display_name, "test-display-name");

        Ok(())
    }

    #[tokio::test]
    async fn basic_fail() -> Result<()> {
        let mut mock = MockSpeech::new();
        mock.expect_get_recognizer().return_once(|_, _| {
            // This time, return an error.
            use gax::error::Error;
            use gax::error::rpc::{Code, Status};
            let status = Status::default()
                .set_code(Code::NotFound)
                .set_message("Resource not found");
            Err(Error::service(status))
        });

        // Create a client, implemented by the mock.
        let client = speech::client::Speech::from_stub(mock);

        // Call our function.
        let display_name = my_application_function(&client).await;

        // Verify the final result of the RPC.
        assert!(display_name.is_err(), "{display_name:?}");

        Ok(())
    }
}

运行 cargo test 以执行单元测试:

cargo test