Monday 25 January 2021

Making Failure Tolerable with ABAP Unit

Right after you learn to include helpful messages in your test failures, you will immediately encounter the problem of failure messages which are incredibly long.

SAP ABAP Tutorial and Material, SAP ABAP Exam Prep, SAP ABAP Career

If only the test runner wasn’t so one-dimensional!

Luckily, while procrastinating on fixing a failing unit test, I found out how to get it to display multiline output.

SAP ABAP Tutorial and Material, SAP ABAP Exam Prep, SAP ABAP Career

To achieve this, we need the fail( ) method which has an extra detail parameter, which will work with multiline strings. \n line endings are needed in the detail string, because \r ends up being displayed as # in the test runner.

If we combine this with the quit-no parameter, we can output multiple failures in a row to add as much diagnostic information about the failure as needed.

And if you still can’t figure out the problem, just add

level = if_aunit_consants=>severity-low to your assertion.

The error is still there, but it is now tolerable.

SAP ABAP Tutorial and Material, SAP ABAP Exam Prep, SAP ABAP Career

Example code
(uses this test wrapper class)

REPORT zfh.

CLASS lcl_test DEFINITION FINAL FOR TESTING
  INHERITING FROM zcl_abap_unit_wrapper
  DURATION SHORT
  RISK LEVEL HARMLESS.

  PRIVATE SECTION.

    "! Method under test
    METHODS is_latin
      IMPORTING text          TYPE string
      RETURNING VALUE(result) TYPE abap_bool.

    METHODS:
      test_latin_knowledge FOR TESTING RAISING cx_static_check.

ENDCLASS.

CLASS lcl_test IMPLEMENTATION.

  METHOD test_latin_knowledge.

    DATA(text) =
|Lorem ipsum dolor sit amet, consectetur adipiscing elit. \r\n| &&
|quam. Vivamus rutrum accumsan quam id rhoncus. \r\n| &&
|Etiam blandit metus sit amet vestibulum hendrerit. \r\n| &&
|Aenean placerat auctor fringilla. Pellentesque iaculis tortor a urna facilisis, \r\n|.

    assert_false(
      act = is_latin( text )
      msg = `Latin test failed`
      quit = quit-no
      level = if_aunit_constants=>severity-low ).

    REPLACE ALL OCCURRENCES OF |\r| IN text WITH ||. " test runner outputs \r as #
    fail( msg = `Failure. Lorem ipsum is not latin.` detail = text quit = quit-no ).

    REPLACE ALL OCCURRENCES OF |lorem ipsum| IN text WITH || IGNORING CASE.
    fail( msg = `This should fix it:` detail = text quit = quit-no ).

    assert_false(
      act = is_latin( text )
      msg = `Latin test failed again.`
      quit = quit-no ).

  ENDMETHOD.

  METHOD is_latin.
    result = xsdbool( text CS `lorem ipsum` ).
  ENDMETHOD.

ENDCLASS.

No comments:

Post a Comment