Luca3317 / OpenLibrary.NET

C# library for OpenLibrary by the InternetArchive
MIT License
15 stars 4 forks source link

OpenLibraryClient interface #9

Closed JeCFe closed 4 months ago

JeCFe commented 5 months ago

Would it be possible to add a public interface for OpenLibraryClient, where OpenLibraryClient would implement this interface. Adding a public interface would allow for easier and better testing of classes that setup the OpenLibraryClient in the constructor or through dependancy injection.

Libraries such as Moq allow for the easy mocking of interfaces during unit tests, which ensure coverage of code without actually sending request off to OpenLibrary, and to allow the tests to more easily test edge cases / error conditions.

With an interface for OpenLibraryClient a testable implementation for when creating / using the client in a constructor would be:

public class Class
{
    private readonly IOpenLibraryCient _client;

    public ClassConstructor(IOpenLibraryCient client = null)
    {
        _client = client switch
        {
            { } => client,
            _ => new OpenLibraryClient()
        };
    }
}

In unit tests a mocked implementation of IOpenLibraryConstructor can be passed when creating the class

Luca3317 commented 5 months ago

I just pushed the interface to a new branch. I dont have any experience with Moq so let me know if it fits all your requirements before I push it to main :)

JeCFe commented 5 months ago

Thanks for the speedy push

From a quick glance, the OpenLibraryClient will need to implement this interface for mocking / DI Like:

namespace OpenLibraryNET
{
    /// <summary>
    /// The main interface to OpenLibrary.<br/>
    /// Instantiates HttpClient internally, as OpenLibraryClient uses cookies.<br/>
    /// To reuse the backing HttpClient, reuse the OpenLibrary instance.
    /// </summary>
    public class OpenLibraryClient : IOpenLibraryClient
    {

If you wanted to make the branch a PR I'd be more than happy to push any chances needed / add few test examples in the repo for ways the new client interface could benefit testing :)

Else I'll hopefully be able to pull the branch down later today and can run it through some Moq examples for confidence that it'll work before committed to main :)

Luca3317 commented 5 months ago

Opened a PR