I am trying to write a unit test using HttpGraphQlTester for the graphQL project, the controller for the project is given below which initializes BatchLoaderRegistry.
public InboundOrderController(BatchLoaderRegistry batchLoaderRegistry) {
batchLoaderRegistry.<String, List<ShipperBooking>>forName("shipperBookingDataLoader")
.registerMappedBatchLoader((Set<String> orderIds, BatchLoaderEnvironment env) ->
Mono.just(shipperBookingService.getShipperBookingByOrderIds(orderIds))
);
}
This shipperBookingDataLoader created in the constructor is being used in the method as given below in the same class.
@SchemaMapping(typeName = "InboundOrder")
public LineItemsQuantitySummary orderLineItemsQuantitySummary( DataLoader<String, List<ShipperBooking>> shipperBookingDataLoader) {
var shipperBookingsList = shipperBookingDataLoader.load(orderId);
}
The test class constructor is this.
InboundOrderGraphQLTest(@Autowired HttpGraphQlTester graphQlTester) {
this.graphQlTester = graphQlTester;
authenticatedTester = graphQlTester
.mutate()
.webTestClient(
client -> client.defaultHeader("x-selected-supplier-id", String.valueOf(SUPPLIER_ID)))
.build();
}
The requirement is to inject shipperBookingDataloader instance in the above class method orderLineItemQuantitySummary through the test method and mock it's behavior.
@Test
void testOrderLineItemQuantitySummaryForInboundOrder() {
var orderId = "1";
var expectedShipperBooking = mockShipperBooking().build();
var expectedInboundOrder = mockInboundOrderBuilder(orderId).build();
var inboundOrderLineItem = Collections.singletonList(
new InboundOrderLineItem("10", 20, "63692157",
"RUYE1036.68842645", "HB-01-A0111", "", 18, 15));
when(inboundOrderService.getByOrderIdForSupplier(orderId, SUPPLIER_ID)).thenReturn(
expectedInboundOrder);
when(inboundOrderService.getInboundOrderLineItems(orderId)).thenReturn(inboundOrderLineItem);
CompletableFuture<List<ShipperBooking>> shipperBookingsFuture = CompletableFuture.completedFuture(
Collections.singletonList(expectedShipperBooking));
when(shipperBookingService.getTotalShippedQuantity(inboundOrderLineItem,
shipperBookingsFuture, "1"))
.thenReturn(CompletableFuture.completedFuture(18));
when(shipperBookingService.getTotalReceivedQuantity(inboundOrderLineItem,
shipperBookingsFuture, "1")).thenReturn(CompletableFuture.completedFuture(15));
var expectedJson = """
{
"orderLineItemsQuantitySummary": {
"totalPlannedQuantity": %d,
"totalReceivedQuantity": %d,
"totalShippedQuantity": %d
}
}
""".formatted(inboundOrderLineItem.get(0).plannedQuantity(),
inboundOrderLineItem.get(0).receivedAtDestinationQuantity(),
inboundOrderLineItem.get(0).shippedFromOriginQuantity());
authenticatedTester
.document("""
{
inboundOrder(id: "1") {
orderLineItemsQuantitySummary {
totalPlannedQuantity
totalReceivedQuantity
totalShippedQuantity
}
}
}
""").execute()
.path("inboundOrder").matchesJson(expectedJson);
}