I am trying to write a unit test which should be successful if the method being tested raises an exception.
The constructor MUST raise an exception if the provided structure doesn't exist in the DDIC.
This was my attempt:
TRY. CREATE OBJECT o_field EXPORTING i_structure_name = 'I_DONT_EXIST' i_field = 'BUKRS'. cl_abap_unit_assert=>fail( msg = 'Invalid structure not detected' ). CATCH zcx_field. ENDTRY.
Test should be successful if the exception is raised.
But unfortunately I can't seem to make this work since the unit test will automatically fail as soon as an exception is raised. SAP says it quite clearly here:
"First of all, ABAP Unit captures unexpected exceptions, even non-catchable exceptions. If an exception occurs, the ABAP unit test fails and the exception is reported as the cause of the failure."
Isn't there a way around it?
How can I write a test which should succeed if an exception is raised?
Thanks in advance,
But unfortunately I can't seem to make this work since the unit test will automatically fail as soon as an exception is raised.
Is the exception defined in the signature of the CONSTRUCTOR?
Its a good practice to keep both logic separate in your unit test method - The one where you call the method of CUT (code under testing) method, and the Unit Test Assert.
So for your testing something like this should give you correct unit test result.
* CUT TRY. CREATE OBJECT o_field EXPORTING i_structure_name = 'I_DONT_EXIST' i_field = 'BUKRS'. CATCH zcx_field into lo_exc. ENDTRY. * Assert cl_abap_unit_assert=>ASSERT_NOT_BOUND( act = lo_exc msg = 'Invalid structure not detected' ).