如何使用 MOQ 来模拟 OpenAIClient 以返回完成响应?我有一个 json 响应,想将其反序列化为
Response<Completions>
。
private OpenAIClient client = // initialize;
private async Task<Response<Completions>> Complete(string model, string prompt) =>
await client.GetCompletionsAsync(model, prompt);
以下返回响应的尝试失败,因为 Completions 类不包含可用于反序列化 json 响应的构造函数 -
private readonly Mock<OpenAIClient> client= new();
client
.Setup(x => x.GetCompletionsAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Response.FromValue(JsonConvert.DeserializeObject<Completions>(completionsJson), Mock.Of<Response>()));
Completions 类构造函数标记为
internal
,Completions 类中的所有对象也是如此。
我知道这是一个老问题,但我遇到了同样的问题,并通过创建一个由替代品/模拟(我正在使用
NSubstitute
)与真实对象混合组成的弗兰肯斯坦对象来解决它。
const string userPrompt = "test";
const string responsePrompt = "response";
// real completion
var completion = OpenAIChatModelFactory.ChatCompletion(
role: ChatMessageRole.User,
content: new ChatMessageContent(ChatMessageContentPart.CreateTextPart(responsePrompt)));
// mocked PipelineResponse
var pipelineResponse = Substitute.For<PipelineResponse>();
// real ClientResult
var completionResponse = ClientResult<ChatCompletion>.FromValue(completion, pipelineResponse);
// mocking my final result
_chatClientMock.CompleteChatAsync(Arg.Any<List<ChatMessage>>(), Arg.Any<ChatCompletionOptions>(), Arg.Any<CancellationToken>())
.Returns(completionResponse);
// call your test service here that invokes _chatClientMock.CompleteChatAsync
// assertions...