How to write unit test for OPEN AI using C# MS Test

Unable to write a unit test for OpenAI SDK

Programming Language: C#

Unit test framework: MS Test

Nuget Package :

  • Owner: OkGoDoIt

used Completions Endpoint

**Issue: ** Unable to MOQ this OpenAI, Passing API Key as dummy and mocked Auth property and added in the constructor but while executing this line we are getting Invalid API Key passed.

But expected here is this should not be executed and not applied MOQ as well.

Can someone help me to write a unit test for this?

Welcome to the forum!

Can you please post your code to help us to help you.

private Mock openAIMock;
private OpenAI openAI;

openAIMock = new Mock();
openAI = new OpenAI(“dummySecret”);


The above method we are calling is one of my own service methods.

Have you been through the documentation here? OpenAI-API-dotnet/ at master · OkGoDoIt/OpenAI-API-dotnet · GitHub

Checked it now and found this section,


While this library does not fully support dependency injection at this time, you may specify an IHttpClientFactory to be used for HTTP requests, which allows for tweaking http request properties, connection pooling, and mocking.

OpenAIAPI api = new OpenAIAPI();
api.HttpClientFactory = myIHttpClientFactoryObject;

If you are talking about this then I need to check how to add MOQ for this and test.

I’d go through there examples one by one, build up your knowledge of the API, it looks to be a fairly well made library and the docs seems fairly well put together, but it’s not an OpenAI library, and so I’m not sure how many people here will be familiar with it, have you tried posting on their help section?