In this short blog I would like to explain how can we write unit test for method which throws exception. Even if it is simple case for many, I got at least one question about it and it means that hints may be useful for others.
As far as I know there is no assertion method or built in feature in ABAP unit test framework that would check if method throws exception. It would be a good candidate to extend framework by the way. We need to handle exception situation ourselves.
Normally if exception is thrown during test method execution, test is marked as failed. We need to avoid error escalation and implement test logic in the way that controls exception and verifies if it actually has occured. I propose two similar variants for that:
If exception is not thrown, we call fail method which makes test not passing. If method that we test raises exception as expected, then fail line will never be reached and test will pass automatically:
TRY. mo_cut->raise_exception( ). cl_abap_unit_assert=>fail( 'Exception did not occur as expected' ) CATCH cx_root. ENDTRY.
We introduce flag that monitors if exception occurs. It has abap_false value by default and it changes only if we enter into CATCH section:
DATA l_exception_occured TYPE abap_bool VALUE abap_false. TRY. mo_cut->raise_exception( ). CATCH cx_root. l_exception_occured = abap_true. ENDTRY. cl_abap_unit_assert=>assert_true( act = l_exception_occured msg = 'Exception did not occur as expected' ).
First variant is shorter but second is more self explained.
If you already use ABAP in eclipse, I recommend to create new template (Window -> Preferences -> ABAP Development -> Source Code Editor -> Templates), call it assert_exception and use it while unit tests creation just by typing "assert", CONTROL + SPACE + assert_exception + ENTER. That helps.
It is also worth to mention that there is already assertion that checks the system status code: cl_abap_unit_assert=>assert_subrc. This method is similar to assert_equals, the difference is that we can skip act parameter as it is by default sy-subrc.