Testable OOP ABAP: Dependency Injection and ABAP Unit
Design ABAP classes so business logic can be tested safely with ABAP Unit.
Explanation
Testable ABAP is easier to maintain and safer to change. Dependency injection means passing a dependency into a class instead of creating it directly inside the class. This allows tests to replace real dependencies with test doubles or fake implementations. ABAP Unit can then test business logic without depending on database state, external RFC calls or UI behavior. This is especially useful for validations, pricing rules, mapping logic and service classes. In S/4HANA and clean core projects, testability becomes more important because changes must be safer and regression risk must be reduced.
Code example
INTERFACE lif_risk_checker. METHODS is_risky_customer IMPORTING iv_kunnr TYPE kunnr RETURNING VALUE(rv_risky) TYPE abap_bool.ENDINTERFACE. CLASS lcl_delivery_service DEFINITION. PUBLIC SECTION. METHODS constructor IMPORTING io_risk TYPE REF TO lif_risk_checker. METHODS should_block IMPORTING iv_kunnr TYPE kunnr RETURNING VALUE(rv_block) TYPE abap_bool. PRIVATE SECTION. DATA mo_risk TYPE REF TO lif_risk_checker.ENDCLASS. CLASS lcl_delivery_service IMPLEMENTATION. METHOD constructor. mo_risk = io_risk. ENDMETHOD. METHOD should_block. rv_block = mo_risk->is_risky_customer( iv_kunnr ). ENDMETHOD.ENDCLASS.Real project scenario
A delivery block service depends on customer risk check. By injecting the risk checker interface, the service can be tested with fake risk results without reading real customer data.
Common mistakes
- Creating dependencies directly inside methods. - Mixing database access and business rule in the same method. - Writing classes that cannot be tested without real SAP data. - Ignoring ABAP Unit for critical reusable logic.
Best practices
- Depend on interfaces for replaceable behavior. - Inject dependencies through constructor or setter. - Keep business rules separate from database access. - Use ABAP Unit for critical logic.
Interview angle
A senior answer should connect OOP design with testing, regression reduction and clean core readiness.