Beyond ABAPdesigned by@Tejoram97
Beyond ABAP / RAP / Extensibility & Testing

Extensibility & Testing

RAP · ABAP Development ·

Open the interactive lesson →
  1. Extensibility: why, who and the key terms
  2. Owner side: make the sales order BO extensible
  3. Extender side: add "Delivery priority" and a check (R19)
  4. Extending SAP's released BOs and node extensions
  5. Testing RAP: what is real, what is a test double (R20)
  6. Testing the BO through EML: validateCustomer, calculateTotal, approve
  7. BO test doubles for classes that use the BO
  8. Testing one handler method directly
  9. Interview questions

This page keeps the sales order app open for change and safe from regressions: a customer project adds the field "Delivery priority" with its own check through RAP extensibility, without modifying the app (R19), and ABAP Unit tests with test doubles protect validateCustomer, calculateTotal and approve (R20).

Part 1 – Extensibility: why, who and the key terms

R-ID

Requirement

Where on this page

R19

A customer project needs an extra field "Delivery priority" without modifying the app

Parts 1–4

R20

Logic is protected by automated tests

Parts 5–8

Why first: the sales order app is finished and running. Then a customer project asks for one more field, R19 – "Delivery priority" (H/M/L) with a check – and the app must not be modified, so that the next version of the app (or an SAP upgrade) doesn't overwrite or break the change.

Extensibility lets someone else add fields, checks or even new child nodes to a business object without changing its source code. Think of a house with wall sockets: the owner decides where the sockets are, and anybody can plug a lamp in later without opening the wall. In RAP the owner of a BO (SAP or your own team) opens these sockets explicitly, and the extension is a separate set of objects that survives every upgrade of the original.

R19 Delivery priority through the plug-in points: five rows (database, CDS data model, behavior, BO tree, projection). Left the socket the sales order BO opens in each layer (extension include, _Extension association, extensible block, extensible entity, extensible projection), right the extension object that plugs in (extend type with zzdlvpriozso, extend view entity with ZZDlvPrioZSO, extension BDEF with zz_validateDlvPrio, node extension, projection extension)

1.1 Key terms

Term

Meaning

Sales order example

Field extension

New field in table, CDS views and UI through the extension include

ZZDlvPrioZSO (H/M/L) on the order header – R19

Behavior extension

Extra validations, determinations, actions, side effects in an extension BDEF with its own behavior pool

zz_validateDlvPrio on save

Node extension

New child entity added to the BO tree (composition in a CDS extension, define behavior for in the BDEF extension)

ZZ_R_OrderNote – notes per order

Projection extension

Exposes new behavior in a service: extension for projection;

use action for an added action

Key user extensibility

Browser apps *Custom Fields* and *Custom Logic*; no ADT needed

A business expert adds a field to SAP's sales document

Developer extensibility

ADT + ABAP Cloud; extends objects released for extension (contract C0) or own BOs that are marked extensible

Extension of I_SalesOrderTP or of ZR_SalesOrder

Extension include (view)

Include structure in the tables + a key-only CDS view on top: the stable anchor that extensions append to

zsales_s_ext_hdr, ZE_SalesOrder

Three columns compare key user extensibility (Custom Fields and Custom Logic apps, YY1_ prefix, level A), developer extensibility (ADT, ABAP Cloud, released objects C0/C1, level A) and classic extensibility (appends, BAdIs, modifications, level B to D). Below, a three-step decision path.

Part 2 – Owner side: make the sales order BO extensible

Four steps, all in the original package, done once by the team that owns the app. Extensibility needs strict mode in the BDEF.

  • Step 1 – extension include structure in the active and the draft table. Its enhancement category and field suffix tell the extender what kind of fields may be appended and how they must be named.
@EndUserText.label : 'Extension include: sales order header'
@AbapCatalog.enhancement.category : #EXTENSIBLE_CHARACTER_NUMERIC
@AbapCatalog.enhancement.fieldSuffix : 'ZSO'
define structure zsales_s_ext_hdr {
dummy_field : abap.char(1);                      " placeholder, an empty structure is not allowed
}

" in zsales_hdr AND zsales_hdr_d (same enhancement category on the table), as the last line:
include zsales_s_ext_hdr;
  • Step 2 – extension include view: a key-only view on the table. Extensions add their fields here, so the base view itself never has to change.
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Extension include view: sales order'
@AbapCatalog.viewEnhancementCategory: [#PROJECTION_LIST]
@AbapCatalog.extensibility: {
extensible: true,
allowNewDatasources: false,
dataSources: ['SalesOrder'],                     " extensions may only read from this alias
elementSuffix: 'ZSO'
}
define view entity ZE_SalesOrder
as select from zsales_hdr as SalesOrder
{
key order_uuid as OrderUUID
}
  • Step 3 – open the base, interface and projection views: an _Extension association from ZR_SalesOrder to the include view, and the same extensibility annotations – data source _Extension in the R_ view, the source alias in ZI_SalesOrderTP and ZC_SalesOrder.
@AbapCatalog.viewEnhancementCategory: [#PROJECTION_LIST]
@AbapCatalog.extensibility: {
extensible: true,
allowNewDatasources: false,
dataSources: ['_Extension'],
elementSuffix: 'ZSO'
}
define root view entity ZR_SalesOrder
as select from zsales_hdr
composition [0..*] of ZR_SalesOrderItem as _Item
association [1..1] to ZE_SalesOrder     as _Extension on $projection.OrderUUID = _Extension.OrderUUID
association [0..1] to I_Customer        as _Customer  on $projection.CustomerID = _Customer.Customer
{
key order_uuid as OrderUUID,
...                                          " all fields as on page 02
_Item,
_Customer,
_Extension
}

" Projection (and interface view ZI_SalesOrderTP the same way): give the source an alias
@AbapCatalog.extensibility: { extensible: true, allowNewDatasources: false,
dataSources: ['SalesOrder'], elementSuffix: 'ZSO' }
define root view entity ZC_SalesOrder
provider contract transactional_query
as projection on ZR_SalesOrder as SalesOrder
  • Step 4 – open the BDEF: the extensible block in the header lists exactly which kinds of behavior an extension may add; every entity that accepts extensions gets extensible too. Make Prepare extensible so added validations also run when the user clicks Save in the draft app, and mark the mapping extensible (only possible with corresponding).
managed implementation in class zbp_r_salesorder unique;
strict ( 2 );
with draft;
extensible
{
with determinations on modify;
with determinations on save;
with validations on save;
with additional save;
}

define behavior for ZR_SalesOrder alias SalesOrder
persistent table zsales_hdr
draft table zsales_hdr_d
etag master LocalLastChangedAt
lock master total etag LastChangedAt
authorization master ( global, instance )
extensible                                         " this entity accepts extensions
{
...                                              " operations and logic as on page 04

draft determine action Prepare extensible
{
validation validateCustomer;
validation Item~validateQuantity;
}

mapping for zsales_hdr corresponding extensible
{
OrderUUID = order_uuid;
...                                            " explicit pairs for fields whose names differ
}
}

The projection BDEF gets a plain extensible; in its header (no block) and extensible per entity. An interface BDEF such as ZI_SalesOrderTP takes extensible; only in its header and covers all its entities. SAP's Flight reference scenario (/DMO/R_AgencyTP, /DMO/I_AgencyTP) shows this pattern.

Part 3 – Extender side: add "Delivery priority" and a check (R19)

The extension lives in another package (often another software component) and never touches the original objects. R19 needs one field and one validation.

3.1 The field through all layers

" 1) persistence: append to the extension include (active and draft table get the column)
extend type zsales_s_ext_hdr with zzx_sales_hdr_zso {
zzdlvpriozso : abap.char(1);
}

" 2) data model: first the include view, then the base view through _Extension
extend view entity ZE_SalesOrder with {
SalesOrder.zzdlvpriozso as ZZDlvPrioZSO
}
extend view entity ZR_SalesOrder with {
_Extension.ZZDlvPrioZSO as ZZDlvPrioZSO
}

" 3) interface and projection + UI annotation directly on the extension element
extend view entity ZI_SalesOrderTP with {
SalesOrder.ZZDlvPrioZSO as ZZDlvPrioZSO
}
extend view entity ZC_SalesOrder with {
@UI.lineItem: [{ position: 90, label: 'Delivery priority' }]
@UI.identification: [{ position: 90, label: 'Delivery priority' }]
SalesOrder.ZZDlvPrioZSO as ZZDlvPrioZSO
}
  • The element name ZZDlvPrioZSO equals the column name zzdlvpriozso apart from upper/lower case. That is deliberate: mapping ... corresponding extensible maps extension fields by name, so no mapping line is needed and none could be added from outside.
  • Prefix ZZ (or YY) and the suffix ZSO from the include keep extension names apart from anything the owner adds later.

3.2 The check: a behavior extension

A separate BDEF of type extension with its own behavior pool. With using interface the extension works through the BO interface ZI_SalesOrderTP (that is why step 3 extended it); for an own BO without an interface the addition is left out.

extension using interface zi_salesordertp
implementation in class zbp_x_salesorder unique;

extend behavior for SalesOrder
{
validation zz_validateDlvPrio on save { create; field ZZDlvPrioZSO; }

extend draft determine action Prepare
{
validation zz_validateDlvPrio;
}
}
CLASS lhc_salesorder DEFINITION INHERITING FROM cl_abap_behavior_handler.
PRIVATE SECTION.
METHODS zz_validatedlvprio FOR VALIDATE ON SAVE
IMPORTING keys FOR SalesOrder~zz_validateDlvPrio.
ENDCLASS.

CLASS lhc_salesorder IMPLEMENTATION.
METHOD zz_validatedlvprio.
READ ENTITIES OF zi_salesordertp IN LOCAL MODE
ENTITY SalesOrder
FIELDS ( ZZDlvPrioZSO ) WITH CORRESPONDING #( keys )
RESULT DATA(orders).

LOOP AT orders INTO DATA(order).
APPEND VALUE #( %tky        = order-%tky
%state_area = 'ZZ_DLV_PRIO' ) TO reported-salesorder.   " clear old message
IF order-ZZDlvPrioZSO <> 'H' AND order-ZZDlvPrioZSO <> 'M' AND order-ZZDlvPrioZSO <> 'L'.
APPEND VALUE #( %tky = order-%tky ) TO failed-salesorder.
APPEND VALUE #( %tky                  = order-%tky
%state_area           = 'ZZ_DLV_PRIO'
%element-ZZDlvPrioZSO = if_abap_behv=>mk-on
%msg = new_message_with_text( severity = if_abap_behv_message=>severity-error
text     = 'Delivery priority must be H, M or L' ) )
TO reported-salesorder.
ENDIF.
ENDLOOP.
ENDMETHOD.
ENDCLASS.

A projection extension is needed only when the extension adds something the service must call, such as an action or a determine action:

extension for projection;

extend behavior for SalesOrder
{
use action zz_checkDlvPrio;                      " e.g. an added determine action
}

An extension can …

Where

Note

Add fields

Append + extend view entity per layer

Only through the extension include view

Add validations, determinations, additional save

extend behavior for

Only the kinds listed in the original extensible { … } block

Add actions, determine actions, field characteristics

extend behavior for

On every entity marked extensible

Add side effects

Extension BDEF

Projection-level support depends on the release – check your release

Add a child node

CDS extension (composition) + define behavior for

The to-parent association is in the new node's view

Change or remove existing behavior

–

Not possible – that would be a modification

Common mistakes

  • Extending a BO that is not marked extensible, or adding a kind of logic the extensible { } block does not list – the extension BDEF won't activate.
  • Forgetting the draft table: the extension include must be in zsales_hdr_d as well, otherwise the new field is lost while editing.
  • A validation added in an extension but not added to Prepare – it runs on activate, but the draft app shows the message only at the very end.
  • Different names for the column and the element – corresponding then can't map the field and the value is never saved.

Part 4 – Extending SAP's released BOs and node extensions

4.1 Node extensions in brief

A new child entity, for example order notes: a view entity ZZ_R_OrderNote with association to parent ZR_SalesOrder as _SalesOrder, a CDS extension of the parent that adds composition [0..*] of ZZ_R_OrderNote as _ZZNote, and in the BDEF extension extend behavior for SalesOrder { association _ZZNote { create; } } plus define behavior for ZZ_R_OrderNote alias ZZNote …. The original BO must be enabled for node extensions – check your release.

Interview tip

Say it in one line: "The original BO decides what can be extended; the extension is a separate object with its own behavior pool, built on released (C0) anchors, so upgrades don't break it."

Part 5 – Testing RAP: what is real, what is a test double (R20)

Why: R20 – the logic must be protected by automated tests, so that the next change (or the R19 extension) can't silently break validateCustomer, calculateTotal or approve. A RAP BO is tested like any ABAP code: with ABAP Unit. The trick is to decide what is real and what is replaced. When you test the BO itself, the RAP runtime and your handlers are real and only the tables are replaced; when you test a class that only uses the BO, the whole BO is replaced. Like a crash test: the car is real, the passenger is a dummy.

R20 testing RAP: lane A, a test class calls EML on ZR_SalesOrder, the real RAP runtime and behavior pool run (lhc_SalesOrder validateCustomer) and SQL/CDS test doubles replace the tables. Lane B, the code under test ZCL_SO_UPLOAD calls EML, which is redirected to a transactional buffer double or a mock EML API. Bottom: testing a handler method directly as a friend with CREATE OBJECT FOR TESTING.

You want to test …

Tool

Replaces

Validations, determinations, actions of your BO (through EML)

ABAP Unit + cl_osql_test_environment

Tables and CDS views read with ABAP SQL (zsales_hdr, zsales_itm, I_Customer)

Logic inside a CDS view entity (calculations, joins)

cl_cds_test_environment

The data sources of that CDS entity

A class that calls your BO with EML (it should not care how the BO works)

cl_botd_txbufdbl_bo_test_env

The whole BO: an in-memory transactional buffer

The same, but you want to fix exact responses and count calls

cl_botd_mockemlapi_bo_test_env

Every EML call: configured input → output, then verify

One handler method in isolation (rare)

Local test class, CREATE OBJECT … FOR TESTING

Nothing – you call the method yourself

5.1 Global vs local test classes – SAP's recommendation

Where a test class lives follows from what it tests. SAP's RAP test guide separates unit tests of the behavior implementation (one handler or saver method, called directly) from integration tests that use the BO from outside through EML – and the two end up in different places.

Test type

Class

Where

Why / tools

Unit test of one handler / saver method (validateCustomer, finalize …)

Local: ltc_… DEFINITION FINAL FOR TESTING

Test Classes tab (test include) of the behavior pool ZBP_R_SalesOrder

lhc_ / lsc_ classes are local to the pool and their methods private: DEFINITION DEFERRED FOR TESTING + FRIENDS, CREATE OBJECT … FOR TESTING (Part 8). SQL / CDS test doubles; legacy function modules → function module test doubles (8.1)

Integration test of the BO through EML (Part 6)

Global: zcl_test_salesorder … PUBLIC … FOR TESTING

Its own class, linked with "! @testing BDEF:ZR_SalesOrder

Runs the whole BO like a consumer (determinations, validations, feature control, COMMIT ENTITIES); cl_osql_test_environment / cl_cds_test_environment. SAP does this in RAP100 exercise 8 and in /DMO/TC_TRAVEL_M

Unit test of a class that only consumes the BO (ZCL_SO_UPLOAD, Part 7)

Local: ltc_… in that class

Test Classes tab of ZCL_SO_UPLOAD

The BO is a dependency: cl_botd_txbufdbl_bo_test_env or cl_botd_mockemlapi_bo_test_env

" Local: Test Classes tab of ZBP_R_SalesOrder - one handler method (Part 8)
" (Local Types: CLASS ltc_validatecustomer DEFINITION DEFERRED FOR TESTING.
"  and lhc_salesorder ... FRIENDS ltc_validatecustomer)
"! @testing BDEF:ZR_SalesOrder
CLASS ltc_validatecustomer DEFINITION FINAL FOR TESTING
RISK LEVEL HARMLESS DURATION SHORT.
PRIVATE SECTION.
DATA cut TYPE REF TO lhc_salesorder.        " CREATE OBJECT cut FOR TESTING
METHODS unknown_customer_fails FOR TESTING RAISING cx_static_check.
ENDCLASS.

" Global: own class pool - the whole BO through EML (Part 6)
"! @testing BDEF:ZR_SalesOrder
CLASS zcl_test_salesorder DEFINITION PUBLIC FINAL CREATE PUBLIC
FOR TESTING RISK LEVEL HARMLESS DURATION SHORT.
PRIVATE SECTION.
METHODS approve_sets_status_a FOR TESTING RAISING cx_static_check.
ENDCLASS.

Part 6 – Testing the BO through EML: validateCustomer, calculateTotal, approve

SAP's approach (RAP100 exercise 8): a test class linked to the BDEF with the ABAP Doc comment "! @testing BDEF:ZR_SalesOrder, SQL test doubles for the data, then EML and assertions on FAILED / REPORTED or on the read result. COMMIT ENTITIES runs the real save sequence – against the doubles. The three tests of R20 each protect one requirement:

R20 three unit tests: validateCustomer protects R6 (unknown customer fails at COMMIT ENTITIES, known customer saves), calculateTotal protects R5 (5 x 10.00 and 2 x 25.00 give NetAmount 100.00 right after MODIFY), approve protects R7 (status N becomes A, status A fails by feature control, a user without ZAO_SO fails by authorization); shared set-up with SQL doubles and ROLLBACK ENTITIES
Timeline of one test class: class_setup creates the SQL doubles, setup clears them and inserts the customer, the test method follows given / when / then, teardown runs ROLLBACK ENTITIES, class_teardown destroys the doubles. Three tips below: link the test with @testing, assert the right thing, never use real data.

6.1 The test class and its set-up

"! @testing BDEF:ZR_SalesOrder
CLASS zcl_test_salesorder DEFINITION PUBLIC FINAL CREATE PUBLIC
FOR TESTING RISK LEVEL HARMLESS DURATION SHORT.
PRIVATE SECTION.
CLASS-DATA sql_env TYPE REF TO if_osql_test_environment.
CLASS-METHODS class_setup.
CLASS-METHODS class_teardown.
METHODS setup.
METHODS teardown.
METHODS insert_order IMPORTING status      TYPE zsales_hdr-status
RETURNING VALUE(uuid) TYPE sysuuid_x16
RAISING   cx_static_check.
METHODS unknown_customer_is_rejected FOR TESTING RAISING cx_static_check.
METHODS total_is_sum_of_items        FOR TESTING RAISING cx_static_check.
METHODS approve_sets_status_a        FOR TESTING RAISING cx_static_check.
METHODS approve_only_for_status_n    FOR TESTING RAISING cx_static_check.
ENDCLASS.

CLASS zcl_test_salesorder IMPLEMENTATION.
METHOD class_setup.
sql_env = cl_osql_test_environment=>create(
i_dependency_list = VALUE #( ( 'ZSALES_HDR' ) ( 'ZSALES_ITM' ) ( 'I_CUSTOMER' ) ) ).
ENDMETHOD.

METHOD setup.
sql_env->clear_doubles( ).
DATA customers TYPE STANDARD TABLE OF i_customer WITH EMPTY KEY.
customers = VALUE #( ( Customer = '0010100001' ) ).
sql_env->insert_test_data( i_data = customers ).   " the only customer validateCustomer can find
ENDMETHOD.

METHOD teardown.
ROLLBACK ENTITIES.                             " never leave instances in the buffer
ENDMETHOD.

METHOD class_teardown.
sql_env->destroy( ).
ENDMETHOD.

METHOD insert_order.                             " an existing order, created by someone else
uuid = cl_system_uuid=>create_uuid_x16_static( ).
DATA orders TYPE STANDARD TABLE OF zsales_hdr WITH EMPTY KEY.
orders = VALUE #( ( order_uuid = uuid  sales_order_id = 'SO-0000001'  customer_id = '0010100001'
status = status  currency = 'EUR'  created_by = 'OTHER_USER' ) ).
sql_env->insert_test_data( i_data = orders ).
ENDMETHOD.

6.2 validateCustomer (R6) – assert FAILED of COMMIT ENTITIES

METHOD unknown_customer_is_rejected.
" given: only customer 0010100001 exists (setup) / when: an order for another customer is saved
MODIFY ENTITIES OF zr_salesorder
ENTITY SalesOrder
CREATE FIELDS ( CustomerID Currency )
WITH VALUE #( ( %cid = 'H1'  CustomerID = '0099999999'  Currency = 'EUR' ) ).

COMMIT ENTITIES RESPONSE OF zr_salesorder
FAILED   DATA(commit_failed)
REPORTED DATA(commit_reported).

" then: the validation stopped the save and marked the field
cl_abap_unit_assert=>assert_not_initial( act = commit_failed-salesorder
msg = 'unknown customer must stop the save' ).
cl_abap_unit_assert=>assert_true( xsdbool( line_exists(
commit_reported-salesorder[ %element-CustomerID = if_abap_behv=>mk-on ] ) ) ).
ENDMETHOD.
  • Add the positive twin (customer 0010100001 → commit_failed initial). If validateCustomer also rejects blocked customers, insert a second customer with the block flag in setup and test it too.
  • A successful COMMIT also runs setSalesOrderId, which draws a real number from the number range (→ 06 · Feature Control, Authorization & Numbering). Keep the number range call in a small class you can replace in tests, or accept used numbers in the development system.

6.3 calculateTotal (R5) – read the field back, no commit needed

METHOD total_is_sum_of_items.
MODIFY ENTITIES OF zr_salesorder
ENTITY SalesOrder
CREATE FIELDS ( CustomerID Currency )
WITH VALUE #( ( %cid = 'H1'  CustomerID = '0010100001'  Currency = 'EUR' ) )
CREATE BY \_Item FIELDS ( ItemNo MaterialID Quantity Unit NetPrice Currency )
WITH VALUE #( ( %cid_ref = 'H1'
%target  = VALUE #(
( %cid = 'I1'  ItemNo = '000010'  MaterialID = 'MAT-001'  Quantity = 5
Unit = 'ST'  NetPrice = '10.00'  Currency = 'EUR' )
( %cid = 'I2'  ItemNo = '000020'  MaterialID = 'MAT-002'  Quantity = 2
Unit = 'ST'  NetPrice = '25.00'  Currency = 'EUR' ) ) ) )
MAPPED DATA(mapped).

" calculateTotal runs ON MODIFY, so the buffer already holds the total
READ ENTITIES OF zr_salesorder
ENTITY SalesOrder
FIELDS ( NetAmount ) WITH VALUE #( ( %tky = mapped-salesorder[ 1 ]-%tky ) )
RESULT DATA(orders).

cl_abap_unit_assert=>assert_equals( exp = CONV zsales_hdr-net_amount( '100.00' )
act = orders[ 1 ]-NetAmount ).
ENDMETHOD.

6.4 approve (R7) – status, feature control and authorization

METHOD approve_sets_status_a.
DATA(uuid) = insert_order( status = 'N' ).     " created by OTHER_USER: four-eyes rule is met

MODIFY ENTITIES OF zr_salesorder
ENTITY SalesOrder
EXECUTE approve FROM VALUE #( ( OrderUUID = uuid ) )   " %is_draft initial = active instance
FAILED DATA(failed).

READ ENTITIES OF zr_salesorder
ENTITY SalesOrder FIELDS ( Status ) WITH VALUE #( ( OrderUUID = uuid ) )
RESULT DATA(orders).

cl_abap_unit_assert=>assert_initial( failed ).
cl_abap_unit_assert=>assert_equals( exp = 'A'  act = orders[ 1 ]-Status ).
ENDMETHOD.

METHOD approve_only_for_status_n.
DATA(uuid) = insert_order( status = 'A' ).     " already approved

MODIFY ENTITIES OF zr_salesorder
ENTITY SalesOrder
EXECUTE approve FROM VALUE #( ( OrderUUID = uuid ) )
FAILED DATA(failed).

" get_instance_features disables approve for status A -> the runtime rejects the call
cl_abap_unit_assert=>assert_equals( exp = if_abap_behv=>cause-disabled
act = failed-salesorder[ 1 ]-%fail-cause ).
ENDMETHOD.
ENDCLASS.
  • Authorization checks run for the user who executes the test. approve needs ZAO_SO and a creator other than the current user (→ 06 · Feature Control, Authorization & Numbering) – that is why insert_order sets created_by = 'OTHER_USER'. Test such rules on purpose, not by accident.
  • To test the "only managers" part, restrict the test user's authorizations with the ABAP Unit authority-check controller (cl_aunit_authority_check=>get_controller( )->restrict_authorizations_to( ... ), reset it in teardown) and expect if_abap_behv=>cause-unauthorized – cheat sheet *14_ABAP_Unit_Tests*; check your release.

You test …

Assert on

A validation

FAILED (and REPORTED) of COMMIT ENTITIES

A determination on modify / an action

READ ENTITIES afterwards and check the field

A determination on save

COMMIT ENTITIES first – it only runs in finalize – then read

Feature control / authorization

%fail-cause in FAILED, or GET PERMISSIONS and %action-approve

Common mistakes

  • No test doubles: COMMIT ENTITIES then really writes to zsales_hdr.
  • No ROLLBACK ENTITIES in teardown – the next test starts with leftovers in the buffer.
  • Asserting REPORTED only: a message alone does not stop the save – FAILED does.
  • Testing an on save determination without COMMIT ENTITIES – it never ran.

Part 7 – BO test doubles for classes that use the BO

The nightly job of R12 uses a class ZCL_SO_UPLOAD that reads a CSV file and creates orders with EML. Its test should not depend on the BO's validations or tables, so the EML calls are redirected to a double (cheat sheet *14_ABAP_Unit_Tests*).

" Option 1 - transactional buffer double: behaves like a simple in-memory BO
" class_setup
txbuf_env = cl_botd_txbufdbl_bo_test_env=>create(
environment_config = cl_botd_txbufdbl_bo_test_env=>prepare_environment_config(
)->set_bdef_dependencies( bdef_dependencies = VALUE #( ( 'ZR_SALESORDER' ) ) ) ).

" setup
txbuf_env->clear_doubles( ).
double = txbuf_env->get_test_double( 'ZR_SALESORDER' ).
" optional: double->insert_test_data( instances = existing_orders ).

" test method: run the code under test, then read what it created - from the double
DATA(created) = NEW zcl_so_upload( )->upload( csv_lines ).          " returns the new keys
READ ENTITIES OF zr_salesorder
ENTITY SalesOrder FIELDS ( CustomerID ) WITH CORRESPONDING #( created )
RESULT DATA(orders).
cl_abap_unit_assert=>assert_equals( exp = 2  act = lines( orders ) ).

" class_teardown
txbuf_env->destroy( ).
" Option 2 - mock EML API: you define the answer to a given EML call and verify the call
eml_env = cl_botd_mockemlapi_bo_test_env=>create(
environment_config = cl_botd_mockemlapi_bo_test_env=>prepare_environment_config(
)->set_bdef_dependencies( bdef_dependencies = VALUE #( ( 'ZR_SALESORDER' ) ) ) ).
double = eml_env->get_test_double( 'ZR_SALESORDER' ).

DATA(in_bldr)  = cl_botd_mockemlapi_bldrfactory=>get_input_config_builder( )->for_read( ).
DATA(out_bldr) = cl_botd_mockemlapi_bldrfactory=>get_output_config_builder( )->for_read( ).
DATA(part)     = in_bldr->build_entity_part( 'ZR_SALESORDER'
)->set_instances_for_read( read_keys ).
DATA(input)    = in_bldr->build_input_for_eml( )->add_entity_part( part ).
DATA(output)   = out_bldr->build_output_for_eml( )->set_result_for_read( read_result ).

double->configure_call( )->for_read( )->when_input( input )->then_set_output( output ).
" ... run the code under test ...
double->verify( )->read( input )->is_called_times( times = 1 ).
  • Use the buffer double when you care about the result ("two orders exist afterwards"), the mock EML API when you care about the call ("exactly one CREATE with these fields"). For MODIFY use for_modify( ) and set_instances_for_create( ) in the same way.

Part 8 – Testing one handler method directly

SAP's RAP test guide treats this as the unit-test level: each handler or saver method (validation, determination, action, saver step) is tested on its own in the Test Classes tab of the behavior pool – the EML tests of Part 6 are the integration level on top. Handler classes are local classes of the behavior pool and have no public constructor. The local test class is declared first with DEFINITION DEFERRED FOR TESTING, the handler names it as a FRIENDS, and the test creates the handler with CREATE OBJECT … FOR TESTING.

" Local Types (CCIMP) of ZBP_R_SalesOrder
CLASS ltc_salesorder DEFINITION DEFERRED FOR TESTING.
CLASS lhc_salesorder DEFINITION INHERITING FROM cl_abap_behavior_handler FRIENDS ltc_salesorder.
PRIVATE SECTION.
METHODS validatecustomer FOR VALIDATE ON SAVE
IMPORTING keys FOR SalesOrder~validateCustomer.
...
ENDCLASS.

" Test Classes (CCAU) of ZBP_R_SalesOrder
CLASS ltc_salesorder DEFINITION FINAL FOR TESTING RISK LEVEL HARMLESS DURATION SHORT.
PRIVATE SECTION.
CLASS-DATA cut       TYPE REF TO lhc_salesorder.               " class under test
CLASS-DATA txbuf_env TYPE REF TO if_botd_txbufdbl_bo_test_env.
CLASS-METHODS class_setup.
ENDCLASS.

CLASS ltc_salesorder IMPLEMENTATION.
METHOD class_setup.
CREATE OBJECT cut FOR TESTING.
" the handler's READ ENTITIES ... IN LOCAL MODE must find data: use a buffer double of the own BO
txbuf_env = cl_botd_txbufdbl_bo_test_env=>create(
environment_config = cl_botd_txbufdbl_bo_test_env=>prepare_environment_config(
)->set_bdef_dependencies( bdef_dependencies = VALUE #( ( 'ZR_SALESORDER' ) ) ) ).
ENDMETHOD.
" test method: insert instances into the double, then
"   cut->validatecustomer( EXPORTING keys = ... CHANGING failed = failed reported = reported ).
" with failed / reported typed RESPONSE FOR FAILED LATE / REPORTED LATE zr_salesorder
ENDCLASS.

Because the methods still read the buffer (READ ENTITIES … IN LOCAL MODE), the test first fills a transactional buffer double of the own BO. Use both levels: unit tests per handler / saver method for the logic, plus EML integration tests (Part 6) that run the whole BO like a consumer.

  • Contract checks: the RAP runtime checks that handlers answer correctly (for example no FAILED entry for a key that was never requested). Since 2311 such violations make unit tests fail; the contract check BEHAVIOR_BAD_HANDLER_RESPONSE exists since 2502 – check your release.

Interview tip

Name both sides: "For the BO itself I unit-test each handler and saver method in the behavior pool's test classes and add EML integration tests with SQL test doubles; for consumers of a BO I use the RAP BO test doubles – the transactional buffer double or the mock EML API."

8.1 Testing an unmanaged BO

In an unmanaged BO (→ 09 · Unmanaged Scenario & Save Variants) the handler and saver methods are the whole BO, and they mostly call legacy code. SAP's unmanaged reference BO /DMO/I_TRAVEL_U shows the approach: local test classes in the behavior pool call every handler and saver method directly, and the legacy function modules are replaced by function module test doubles.

" Test Classes tab of ZBP_R_SalesOrder (unmanaged, Parts 2-4 of page 09)
" Local Types: CLASS ltc_read DEFINITION DEFERRED FOR TESTING.
"              lhc_SalesOrder ... FRIENDS ltc_read
"! @testing BDEF:ZR_SalesOrder
CLASS ltc_read DEFINITION FINAL FOR TESTING RISK LEVEL HARMLESS DURATION SHORT.
PRIVATE SECTION.
CLASS-DATA fm_env TYPE REF TO if_function_test_environment.
DATA cut TYPE REF TO lhc_SalesOrder.
CLASS-METHODS class_setup.
METHODS setup.
METHODS teardown.
METHODS legacy_order_is_returned FOR TESTING RAISING cx_static_check.
ENDCLASS.

CLASS ltc_read IMPLEMENTATION.
METHOD class_setup.                   " every CALL FUNCTION 'Z_SO_READ' hits the double
fm_env = cl_function_test_environment=>create(
function_modules = VALUE #( ( 'Z_SO_READ' ) ) ).
ENDMETHOD.

METHOD setup.
CREATE OBJECT cut FOR TESTING.
CLEAR lcl_buffer=>orders.             " static buffer: every test starts empty
ENDMETHOD.

METHOD teardown.
fm_env->clear_doubles( ).
ENDMETHOD.

METHOD legacy_order_is_returned.
DATA keys     TYPE TABLE FOR READ IMPORT zr_salesorder\\salesorder.
DATA result   TYPE TABLE FOR READ RESULT zr_salesorder\\salesorder.
DATA failed   TYPE RESPONSE FOR FAILED EARLY zr_salesorder.
DATA reported TYPE RESPONSE FOR REPORTED EARLY zr_salesorder.
DATA(uuid)  = cl_system_uuid=>create_uuid_x16_static( ).
DATA(order) = VALUE zsales_hdr( order_uuid = uuid  customer_id = '0010100001' ).

" given: the buffer is empty and the legacy read knows the order
DATA(fm_read) = fm_env->get_double( 'Z_SO_READ' ).
DATA(input)   = fm_read->create_input_configuration(
)->set_importing_parameter( name = 'IV_ORDER_UUID' value = uuid ).
DATA(output)  = fm_read->create_output_configuration(
)->set_exporting_parameter( name = 'ES_HEADER' value = order ).
fm_read->configure_call( )->when( input )->then_set_output( output ).

" when
keys = VALUE #( ( OrderUUID = uuid ) ).
cut->read( EXPORTING keys     = keys
CHANGING  result   = result
failed   = failed
reported = reported ).

" then
cl_abap_unit_assert=>assert_initial( failed ).
cl_abap_unit_assert=>assert_equals( exp = order-customer_id
act = result[ 1 ]-CustomerID ).
ENDMETHOD.
ENDCLASS.

Part 9 – Interview questions

Q1. What must the owner of a BO do before anyone can extend it?

Open sockets in every layer: an extension include structure in the active and draft table, a key-only extension include view, an _Extension association and @AbapCatalog.extensibility on the R_, I_ and C_ views, and in the BDEF (strict mode) an extensible { ... } block listing what may be added, extensible on each entity, Prepare extensible and mapping ... corresponding extensible. Nothing the owner didn't open can be extended.

Q2. How do you add a field like "Delivery priority" to your own RAP app without modifying it?

In a separate package: extend type on the extension include (the column appears in the active and draft table), extend view entity on the include view, the base view (through _Extension), the interface and the projection with the UI annotations. A check goes into an extension BDEF (extension using interface ..., extend behavior for) with its own behavior pool, and into extend draft determine action Prepare.

Q3. How do you extend a released SAP BO?

If the key user app Custom Fields is enough, use it – no code. Otherwise developer extensibility in ADT: fields through the extension include views SAP ships, logic through a BDEF extension (extension using interface I_…TP) with its own behavior pool. Only objects released for extension (C0) and only what the original marked extensible can be extended.

Q4. Scenario: the business wants a "Priority" field on SAP's standard sales order in S/4HANA Cloud.

First the key user app Custom Fields: add the field to the sales document business context and enable it for UI and APIs. If logic is needed (e.g. priority H only for big orders), a developer extension: field through the extension include view, a validation in a BDEF extension of the released interface. Never a modification – that is not possible in the public cloud anyway.

Q5. Why does an extended validation have to be added to Prepare?

In a draft app the user clicks Save, which calls the determine action Prepare before Activate. Only the validations listed in Prepare run at that moment and show their messages on the draft. An extension adds its validation with extend draft determine action Prepare, which works only if the owner declared Prepare extensible.

Q6. How do you test a RAP BO?

With ABAP Unit: a test class linked to the BDEF ("! @testing BDEF:...), SQL or CDS test doubles for the data, and EML calls. For validations I assert FAILED and REPORTED of COMMIT ENTITIES; for determinations on modify and actions I read the field back; for feature control and authorization I check %fail-cause or GET PERMISSIONS. teardown runs ROLLBACK ENTITIES.

Q7. Transactional buffer double or mock EML API?

Both replace a whole BO for a class that only consumes it. The transactional buffer double (cl_botd_txbufdbl_bo_test_env) behaves like a simple in-memory BO, so I assert on the result. The mock EML API (cl_botd_mockemlapi_bo_test_env) returns configured outputs for a given input and lets me verify how often a call was made, so I assert on the call.

Q8. Why can a test of the approve action fail although the code is correct?

Because the runtime checks feature control and authorization for the test user: approve is disabled for orders that are not in status N, needs the authorization object, and the four-eyes rule rejects orders the same user created. A good test sets up the data on purpose (status N, another creator) and tests the rejections explicitly, e.g. with the ABAP Unit authority-check controller.

🏠 Start Here · ◀ 11 · Files & Integration · 13 · Quality & Clean Core ▶ · Sections: CORE ABAP | OOPS ABAP | ABAP on HANA | Clean Core | RAP | ABAP Points | SAP Fiori | SAPUI5 | Mobile Development (MDK) | BTP Foundations | BTP Development | CAP | SAP Build | ABAP on BTP | Integration Suite | SAP Business AI | SAP BASIS | Security | SAP SDLC

Functional: FICO ABAP | TRM ABAP | VIM | SAP BIS | SD ABAP | MM ABAP | PP ABAP | QM ABAP | PM ABAP | PS ABAP | EWM | TM ABAP | GTM ABAP | EHS ABAP | HR ABAP | BW | SAP Datasphere | SAP Business Data Cloud | SAP MDG | SAP Analytics Cloud | SAP Ariba | SAP CX | SAP IBP