jeudi 16 janvier 2020

How to unit test a class having a dependency on OutboundDeliveryV2ServiceBatch?

I am trying to write unit tests for a custom class, let's call it, OutboundDeliveryUpdater which has a dependency on com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces.outbounddeliveryv2.batch.OutboundDeliveryV2ServiceBatch (it is a class field). The requirement is to update multiple Outbound Delivery Items on the S4 system. The method in OutboundDeliveryUpdater which performs the update looks like this (omitting exception handling for brevity):

OutboundDeliveryV2ServiceBatchChangeSet changeSet = outboundDeliveryService.beginChangeSet();

itemsForUpdation.forEach(changeSet::updateOutbDeliveryItem);

changeSet.endChangeSet();

BatchResponse batchResponse = outboundDeliveryService.execute(destination);

boolean isUpdateSuccessful batchResponse.get(0).isSuccess();

Now the problem is that while writing unit test for the above code, following things have to be mocked:

  1. outboundDeliveryService.beginChangeSet() and outboundDeliveryService.execute(destination)
  2. destination, which is an instance of HttpDestination
  3. changeSet.updateOutbDeliveryItem()
  4. batchResponse.get()

This makes the unit test very complicated. We have to mock a real dependency (outboundDeliveryService) and the objects that are returned by the methods which are executed on that dependency (changeSet, batchResponse). This seems to be a classic violation of Law of Demeter and the code demonstrates the flaw of digging into collaborators and this is the reason why it is becoming hard to write unit tests for this code.

Is there a better way of writing:

  1. The unit tests for this code to prevent all this complexity?
  2. If not then is there a better way of designing OutboundDeliveryUpdater so that the issue is solved? For e.g. OutboundDeliveryUpdater can have a dependency on a new class, let's say, SomeService which acts as a facade and hides the complexity of OutboundDeliveryV2ServiceBatchChangeSet. But this again will shift the complexity of testing from OutboundDeliveryUpdater's unit test to SomeService's test.

Aucun commentaire:

Enregistrer un commentaire