任何人都可以建议一些方法来模拟 Go 中的 Google Cloud Speech-v2 gRPC 语音客户端吗

问题描述 投票:0回答:1
import (
    "context"
    "fmt"
    package speech ("cloud.google.com/go/speech/apiv2")
)

func GSTTClient() {
    ctx := context.Background()
    opts := []option.ClientOption{}
    if client, err := speech.NewClient(ctx, opts...); err != nil {
        fmt.Printf("failed to create new client")
    } else {
        return client
    }
}

这是我如何创建 gRPC 客户端的代码示例。但我无法弄清楚如何返回一个模拟客户端,我将在单元测试用例中进一步使用它。

当前测试用例正在进行网络调用,该调用获取实际的 google stt gRPC 客户端。但我期待一个模拟客户。

go google-cloud-speech
1个回答
0
投票
package main

import (
    "context"
    "fmt"
    "os"

    speech "cloud.google.com/go/speech/apiv2"
    speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1"
)

type SpeechClientInterface interface {
    Recognize(ctx context.Context, req *speechpb.RecognizeRequest, opts ...interface{}) (*speechpb.RecognizeResponse, error)
}

type MockSpeechClient struct{}
func (m *MockSpeechClient) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, opts ...interface{}) (*speechpb.RecognizeResponse, error) {
    return &speechpb.RecognizeResponse{}, nil
}

func NewMockSpeechClient() *MockSpeechClient {
    return &MockSpeechClient{}
}

func main() {
    ctx := context.Background()
    client := NewMockSpeechClient()

    req := &speechpb.RecognizeRequest{}
    resp, err := client.Recognize(ctx, req)
    if err != nil {
        fmt.Fprintf(os.Stderr, "failed to recognize: %v", err)
        return
    }
    fmt.Printf("Response: %v", resp)
}
© www.soinside.com 2019 - 2024. All rights reserved.