How to assert an exception message in ABAP Unit test

How may have the requirement to assert in a unit test an exception, which has been thrown. To properly test, if the thrown message is equal to the expected message, we can check the message ID.

So first, let’s assume that we have a method, which throws a custom exception.

  METHOD save.
    " ... more stuff here

    INSERT zanytable FROM ls_anycontent.

    IF sy-subrc EQ 0.
      rv_result = abap_true.
    ELSE.
      RAISE EXCEPTION TYPE zcx_custom_exception
        EXPORTING
          textid = zcx_custom_exception=>could_not_save_payload.
    ENDIF.
  ENDMETHOD.

Our exception class contains some texts, which are associated with a global message class.

The exception IDs are linked with a message class, where it gets the texts from.
The message class contains the translated texts and also the message numbers (MSGNO).

Now that we have setup these two objects, we can assert in our local test unit class the exception as follows.

TRY.
    " Execute here a method, which results in our custom or failed 
  CATCH zcx_custom_exception INTO DATA(lx_data).
    cl_abap_unit_assert=>assert_equals(
      " Fetching the message number from the actual parameter
      act = lx_data->if_t100_message~t100key-msgno
      
      " Fetching the message number from the exception class
      exp = zcx_custom_exception=>could_not_save_payload-msgno
    ).
ENDTRY.

This method above, will now check if both message numbers are the same. In this example 001 equals 001. You may also could check if the message ID (ZFI_CUSTOM_MESSAGE) is the same with an additional assert.

cl_abap_unit_assert=>assert_equals(
  " Fetching the message id from the actual parameter
  act = lx_data->if_t100_message~t100key-msgid
  
  " Fetching the message id from the exception class
  exp = zcx_custom_exception=>could_not_save_payload-msgid
).

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ad blocker detected

We have detected that you are using extensions to block ads. Please support us by disabling your ad blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock