crowdin / crowdin-api-client-dotnet

.NET client library for Crowdin API
https://www.nuget.org/packages/Crowdin.Api/
MIT License
52 stars 27 forks source link

Mocking data for unit testing. #275

Open EvilKot opened 1 month ago

EvilKot commented 1 month ago

Hello 👋

In current implementation making API calls is done through methods in ApiExecutor classes, such as SourceFilesApiExecutor, SourceStringsApiExecutor, etc.

Example:

ICrowdinApiClient client = /* Initialize client */

var sourceFiles = await client.SourceFiles.ListFiles<FileInfoCollectionResource>(1, 25, 0);
var sourceStrings = await client.SourceStrings.ListStrings(1, 25, 0);

Since ICrowdinApiClient defines executor properties as concrete classes and those classes have non-virtual methods, it's not possible to mock a data returned by a client for unit testing purposes.

Moreover, since send request methods of the client are marked as internal, it's also not possible to at least mock the returned JSON, similarly to how it's done in Crowdin client unit tests.

Desired use case example:

using Moq;
using Crowdin.Api;

// ...

private Mock<ICrowdinApiClient> _clientMock;

[SetUp]
public void Setup()
{
    _clientMock = new Mock<ICrowdinApiClient>();
}

[Test]
public async Task ShouldPass()
{
    var expectedResponse = /* Assign data */
    _clientMock.Setup(client => client.SourceStrings.ListStrings(/* setup */).ReturnsAsync(expectedResponse );
                                                 ^^^^
                                                 Moq - Non-overridable members may not be used in setup / verification expressions

One of suggestions is to define interface for every ApiExecturor class or simply mark methods as virtual. Current workaround is to define a wrapper class and proxy calls to Crowdin Api client.

WDYT?

andrii-bodnar commented 3 weeks ago

@innomaxx please take a look

innomaxx commented 2 weeks ago

Hi @EvilKot. Good idea!

One of suggestions is to define interface for every ApiExecutor class or simply mark methods as virtual.

I suggest the 1st approach: define an interface for each API Executor. It's not so time-consuming, I can deal with it soon.

@andrii-bodnar what's your opinion?

andrii-bodnar commented 1 week ago

Sounds good to me!