Skip to content

Mocking Service Clients

Connie Yau edited this page Jan 23, 2020 · 2 revisions

Customers using the Azure SDK client libraries can mock service clients using Mockito with org.mockito.plugins.MockMaker. More information can be found at Mock the unmockable: opt-in mocking of final classes/methods.

Steps

  1. Create a file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
  2. In the file, put a single line.
  • mock-maker-inline

Example

Consider an application that uses Azure Event Hubs to fetch telemetry and the end user wants to test that their TelemetryEvents class properly transforms EventData to TelemetryEvent.

Product code

public class TelemetryEvents {
    private final EventHubConsumerAsyncClient consumerClient;
    public TelemetryEvents (EventHubConsumerAsyncClient consumerClient) {
        this.consumerClient = consumerClient;
    }
    
    public Flux<TelemetryEvent> getEvents() {
        return consumerClient.receiveFromPartition("1", EventPosition.latest())
                .map(event -> new TelemtetryEvent(event));
    }
}

Test code

import reactor.test.publisher.TestPublisher;
import reactor.test.StepVerifier;

import static com.azure.messaging.eventhubs.*;
import static org.mockito.Mockito.*;

public class TelemetryEventsTest {
    @Test
    public void canGetEvents() {
        // Arrange

        // After following the instructions in "Steps" section
        EventHubConsumerAsyncClient consumerClient = mock(EventHubConsumerAsyncClient.class);

        TestPublisher<EventData> eventsPublisher = TestPublisher.createCold();
        eventsPublisher.emit(new EventData("Foo"), new EventData("Bar"));
        when(consumerClient.receiveFromPartition(eq("1"), eq(EventPosition.latest())).thenReturn(eventsPublisher.flux());

        TelemetryEvents telemetryEvents = new TelemetryEvents(consumerClient);

        // Act
        StepVerifier.create(telemetryEvents.getEvents())
            .assertNext(event -> isMatchingTelemetry(event))
            .assertNext(event -> isMatchingTelemetry(event))
            .verifyComplete();        
    }
}
Clone this wiki locally