OOP ABAP Part 9: Dependency Injection and ABAP Unit
Preview · a free account unlocks the full lesson
Make classes testable with dependency injection: constructor injection, optional parameters with defaults, injection through a factory, and ABAP Unit test doubles written by hand or generated with CL ABAP TESTDOUBLE.
In this lessonShow sectionsHide sections
Visual overview
Explanation
Part 8 of this series created objects inside factories; now it's time to look at the consumer side — how a class receives those objects, and how tests pass in fakes instead. (Part 10 of the Modularization series introduced the basics of ABAP Unit; this lesson focuses on the object-oriented design side of the same idea.) Dependency injection means a class receives the objects it needs — a DAO, a logger, a tax calculator — instead of creating them itself.
The problem without it looks like this: METHOD constructor. CREATE OBJECT mo_dao TYPE zcl_order_dao. ENDMETHOD. — the class is hard-wired to real database access, and testing it would require specific data to exist in the database, which changes over time and differs between systems.
Constructor injection is the clearest form of the fix: METHODS constructor IMPORTING io_dao TYPE REF TO zif_order_dao. Production code, or a factory, passes in zcl_order_dao, while a test passes in ltd_order_dao, a test double; either way, the class itself only ever knows the interface.
To avoid breaking existing callers, injection can be made optional with a default: make the parameter OPTIONAL, and inside the constructor, write IF io_dao IS BOUND, use it, ELSE create the real one. Existing callers stay fully compatible, while tests can still inject their own double.
Create a free account to keep reading
You have read the opening of this lesson. A free ERPClimb account unlocks the rest of it, every other lesson and topic, and your learning history, so you can pick up exactly where you stopped. No card needed.
- Full explanation
- Code example
- Real project scenario
- Common mistakes
- Best practices
- Interview angle
One tap with Google works too. Every topic keeps its first lesson open to everyone.
Keep exploring
Interview questions on this topic
Related SAP topics
Check before use: lesson examples are educational, not a guarantee of correctness for your SAP edition or release. Sample code has not been executed on your SAP system. Confirm API availability, syntax, authorizations and business impact in an approved development or test environment.