Search code examples
unit-testingoopconstructorabap

Why constructor gets called again after the SUBMIT?


I have the following global class which is supposed to hold a reference to IF_OSQL_TEST_ENVIRONMENT as a static attribute.

CLASS zcl_static_holder DEFINITION
  PUBLIC
  FINAL
  CREATE PUBLIC .

  PUBLIC SECTION.

    CLASS-DATA sr_osql_test_environment TYPE REF TO if_osql_test_environment .

    CLASS-METHODS class_constructor .
    CLASS-METHODS set_osql_test_environment
      IMPORTING
        !ir_osql_test_environment TYPE REF TO if_osql_test_environment .
  PROTECTED SECTION.
  PRIVATE SECTION.
ENDCLASS.



CLASS zcl_static_holder IMPLEMENTATION.


  METHOD class_constructor.
    BREAK-POINT.
  ENDMETHOD.


  METHOD set_osql_test_environment.
    sr_osql_test_environment = ir_osql_test_environment.
  ENDMETHOD.
ENDCLASS.

Now I set this static attribute in a unit test in the following program. The class constructor of the above class gets called before the static attribute is initialised through the setter. However after sumbitting the report the class constructor is called for the second time and the static attribute of course is not set anymore.

REPORT zsubmit_with_static_holder.

CLASS lcl_test DEFINITION FINAL FOR TESTING
  RISK LEVEL HARMLESS DURATION SHORT.
  PUBLIC SECTION.
    METHODS:
      test FOR TESTING.
ENDCLASS.

CLASS lcl_test IMPLEMENTATION.
  METHOD test.
    DATA(lr_osql_test_environment) = cl_osql_test_environment=>create(
      VALUE #( ( 'T100' ) )
    ).
    zcl_static_holder=>set_osql_test_environment( lr_osql_test_environment ).

    SUBMIT zsubmit_with_static_holder
      AND RETURN.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  IF zcl_static_holder=>sr_osql_test_environment IS NOT BOUND.
    WRITE / 'Not bound.'.
  ENDIF.
  SELECT COUNT( * ) FROM t100.
  IF sy-subrc <> 0.
    WRITE / 'No entries. Table mocked!'.
  ENDIF.

Why is so? How can I get it to work? I found something about database LUWs and SAP LUWs and that it could be solved by shared memory object which on the other hand look very complex for such an easy usage in a unit test.


Solution

  • SUBMIT starts a new Internal Session and so all programs are loaded again.

    Better move the code after start-of-selection in a class and call this class instead of using SUBMIT.

    If you can't avoid SUBMIT, I think there's no solution, but who knows.