Search code examples
unit-testingazure-cognitive-search

Any working examples of Mocking calls to Azure Cognitive Search via .NET SDK?


Looking for working examples of mocking calls to Azure Cognitive Search via .NET SDK? To be used in unit tests of the application that calls the search API. Using the Document based, v11 version of the SDK.


Solution

  • We don't currently have anything specific to Azure Cognitive Search SDK, but all our Azure.* SDKs following certain guidelines that make sure general samples like this (adapted for Search):

    // Create a mock response
    var mockResponse = new Mock<Response>();
    
    // Create a client mock
    var mock = new Mock<SearchClient>();
    
    // Setup client method
    mock.Setup(c => c.GetDocument<Model>("Name", default, default))
        .Returns(Response.FromValue(new Model { Name = "name", Value = 1 }, mockResponse.Object));
    
    // Use the client mock
    SearchClient client = mock.Object;
    Model m = client.GetDocument<Model>("Name");
    

    We also have more mocking samples.

    If you want to use the system we use for recording and playing back longer tests from JSON files, see our tests under the "test" directory, namely the MockTransport class.