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.
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
).
Leave a Reply