ABAP Unit and Test Doubles
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A unit test is a small program that calls one piece of your code, with input that you choose, and checks that the result is the one you expect. Once the tests exist, you can change the code tomorrow and find out in seconds whether you broke something that worked yesterday. A newcomer meets unit tests the first time a team asks for them before a transport may be released, and again when a class that reads the database or asks a user for input turns out to be hard to test. ABAP has its own framework for this, called ABAP Unit, and a family of helpers called test double frameworks that replace the parts of a program that a test should not touch, such as a database table or another class. After reading this page you can write a test class with test methods and a fixture, check results with assertions, replace a dependency with a test double that you wrote or that a framework generated, test code that reads a database table, and know which tool exists for CDS views, RAP business objects and old code that was never designed for testing. The page is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). ABAP Unit is part of the language and works in ABAP Cloud, in classic Standard ABAP, on premise and in the Public Edition; the sections on the ABAP Unit Browser and on test seams are marked where they belong to the classic side.
Before you read
-
Classes and Objects: classes, methods, constructors and the
FRIENDSaddition. -
Interfaces and Inheritance: why code that talks to an interface can be given another class behind it.
-
Class-Based Exceptions:
TRY,CATCHand exception classes, which the example uses. -
ABAP SQL Basics: the
SELECTstatement, which the database examples test. -
ABAP Development Tools (ADT): the Eclipse tooling in which tests are written and run.
Key terms
-
Unit test: a test of one small unit of code, run automatically and without any person making a decision.
-
ABAP Unit: the ABAP framework that finds, runs and evaluates the tests that you write as test classes.
-
Test class: a class marked
FOR TESTINGthat holds test methods and is never part of the production code. -
Fixture: the starting situation of a test, prepared by the special methods
setupandclass_setupand cleaned up byteardownandclass_teardown. -
Assertion: a check inside a test, written as a call of
CL_ABAP_UNIT_ASSERT, that fails the test when the result is not the expected one. -
Depended-on component: anything the code under test uses that is not part of the test, such as another class, a database table or an authority check.
-
Test double: an object or a table that stands in for a depended-on component during a test.
-
Injection: the act of giving the code under test a test double instead of the real component.
-
Test seam: a marked piece of production code that a test can replace with other statements.
What a unit test looks like
A good test has three parts, which the SAP cheat sheet calls given, when and then. The given part prepares the situation:
it creates the object to be tested and whatever it needs. The when part calls the one method under test. The then
part compares the result with the expected result and reports a difference. In ABAP the then part is a call of a
static method of the class CL_ABAP_UNIT_ASSERT, for example assert_equals.
The tests are written as ordinary ABAP classes with the addition FOR TESTING. They are kept apart from the code they
test, in a local test class of the same development object. For a global class, ADT shows them on the tab Test Classes,
which holds a special include of the class pool. The Keyword Documentation states the three rules that follow from this:
the source of a test class is not part of the production code of its program, it is not generated in production
systems, and production code cannot address a test class. The only exception is that a production class can name a test
class as a friend, so that a test may read private attributes.
The example used on this page
The Expense claims application has a rule: a claim above a spending limit is rejected. The limit does not live in the
class that applies the rule. It comes from a policy that a company can change, and in a real system it would be read
from a customizing table or a service. The class that applies the rule therefore asks a small interface for the limit,
and the tests give it a different answer than the real one. The interface has two methods; the tests need only the first,
which is why PARTIALLY IMPLEMENTED appears later.
The listings in this section and the next run in the local playground, which is a community tool and not SAP software. It
has the ABAP Unit class CL_ABAP_UNIT_ASSERT, a re-implementation of the test double classes and an in-memory database,
but no ABAP Dictionary tools, no CDS and no RAP. The playground table ZEXP_CLAIM is a reduced version of the table of
the running example: it has only CLAIM_ID, STATUS and AMOUNT (an integer). The names zcl_exp_claim_limit_check,
zif_exp_limit_source and zcx_exp_limit_exceeded are invented for this page; they are not the validator class of the
page on classes and objects, which holds its limit itself.
INTERFACE zif_exp_limit_source PUBLIC.
METHODS get_limit
RETURNING VALUE(limit) TYPE i.
METHODS get_name
RETURNING VALUE(name) TYPE string.
ENDINTERFACE.
CLASS zcx_exp_limit_exceeded DEFINITION
PUBLIC
INHERITING FROM cx_static_check
FINAL
CREATE PUBLIC.
PUBLIC SECTION.
DATA limit TYPE i READ-ONLY.
METHODS constructor
IMPORTING limit TYPE i.
ENDCLASS.
CLASS zcx_exp_limit_exceeded IMPLEMENTATION.
METHOD constructor.
super->constructor( ).
me->limit = limit.
ENDMETHOD.
ENDCLASS.
CLASS zcl_exp_claim_limit_check DEFINITION
PUBLIC
FINAL
CREATE PUBLIC.
PUBLIC SECTION.
METHODS constructor
IMPORTING limit_source TYPE REF TO zif_exp_limit_source.
METHODS check
IMPORTING amount TYPE i
RAISING zcx_exp_limit_exceeded.
PRIVATE SECTION.
DATA limit_source TYPE REF TO zif_exp_limit_source.
ENDCLASS.
CLASS zcl_exp_claim_limit_check IMPLEMENTATION.
METHOD constructor.
me->limit_source = limit_source.
ENDMETHOD.
METHOD check.
DATA(limit) = limit_source->get_limit( ).
IF amount > limit.
RAISE EXCEPTION NEW zcx_exp_limit_exceeded( limit = limit ).
ENDIF.
ENDMETHOD.
ENDCLASS.
The constructor receives the limit source from outside. This single decision is what makes the class testable, and it has a name: constructor injection. The next sections come back to it.
Anatomy of a test class
The addition FOR TESTING turns a class into a test class. Two further additions describe the test, and ABAP Unit
checks them before it runs anything.
| Addition | Meaning |
|---|---|
|
The test changes neither system settings nor persistent data. |
|
The test changes persistent data, for example by writing to a database table. |
|
The test changes system settings or customizing data. This is the default when the addition is left out. |
|
An imperceptible run time of a few seconds is expected. |
|
A noticeable run time of around a minute is expected. |
|
A very noticeable run time of more than a minute is expected. |
A test whose risk level is higher than the administration allows is not run. The administrator sets the allowed level
and the upper limit of each duration in the client setup of ABAP Unit, transaction SAUNIT_CLIENT_SETUP. Declare the
duration that you really expect, not the upper limit, because a test that is slower than its declaration is aborted.
Inside the class you declare test methods with METHODS name FOR TESTING. The framework calls each test method as a
separate test. Four more methods with fixed names make up the fixture, the starting situation of the tests. They are
private, have no parameters and never carry FOR TESTING.
| Method | Runs |
|---|---|
|
An instance method that runs before every test method. |
|
An instance method that runs after every test method. |
|
A static method that runs once before all tests of the class. |
|
A static method that runs once after all tests of the class. |
A test class may also have helper methods, attributes and any other component. You can give a test method or a test
class a test relation to a repository object that has no test classes of its own, with the ABAP Doc comment tag
@testing. Test methods are private or protected; the framework can still call them, because a test class offers
friendship to the test driver.
Assertions: CL_ABAP_UNIT_ASSERT
A test method decides whether it passed through the static methods of CL_ABAP_UNIT_ASSERT. A test that raises no
failure passes. The most used methods are in this table.
| Method | Checks |
|---|---|
|
Two data objects are equal: the actual value in |
|
Two elementary data objects are different. |
|
A boolean value is true or false. |
|
A data object has, or does not have, its initial value. |
|
A reference variable points, or does not point, to an object. |
|
The return code |
|
An internal table contains a given line. |
|
A number is inside a range. |
|
Fails the test at once; used where the code must not be reached. |
|
Skips the test because a prerequisite is missing. |
Most methods take the parameters act (the value to check), exp (the expected value), msg (a text shown when the check
fails) and quit, which decides whether the test ends at the first failure. Give every assertion a short message when the
reason for a failure is not obvious from the values. Do not pass system fields such as sy-subrc as the actual
parameter, because the assertion can change them; copy the field into a variable first, or use ASSERT_SUBRC.
Depended-on components and test doubles
The class under test calls get_limit of another object. The Keyword Documentation and the SAP Help Portal call the code
that you test the object under test, and everything it relies on a depended-on component, in short DOC. A test controls
the object under test through its front door, its public methods: it chooses the input and reads the result. The
object under test also talks to its depended-on components through a back door: it receives answers from them and sends
calls to them. A test double is the key to the back door. It replaces the real component during the test, so that the
test decides what the component answers (indirect input) and can see what the object under test sent to it (indirect
output).
To use a test double you create it, optionally configure what it answers, and inject it. These are the injection techniques named by SAP.
-
Constructor injection: the double is a parameter of the constructor, as in the example class.
-
Setter injection: the double is passed to a setter method.
-
Parameter injection: the double is an optional parameter of the method under test.
-
Private injection or friend access: the test class is a friend of the class under test and writes the private attribute that holds the dependency.
-
Test seams: a marked piece of the production code is replaced for the test (see the last section).
Which tool builds the double depends on what kind of component you replace.
| The component is | Use | Reads or writes |
|---|---|---|
A class or an interface |
A hand-made double class, or the Object Oriented Test Double Framework ( |
Answers to method calls and the calls received |
A database table, a CDS view or other data source, read and write |
The ABAP SQL Test Double Framework ( |
ABAP SQL statements, reads and writes |
A CDS view entity, read only |
The CDS Test Double Framework ( |
Logic written in the CDS entity |
A RAP business object used through EML |
The RAP business object test double frameworks |
Calls of |
Any other statement, such as an authority check |
Test seams, or the authority check test helper |
One statement of the production code |
A test with a hand-made double
The first test class replaces the limit source with a class that the test itself defines. The class lcl_limit_double
implements the interface zif_exp_limit_source. The addition PARTIALLY IMPLEMENTED of INTERFACES is allowed only in
test classes and lets the double implement just get_limit; if the code under test called the unimplemented
get_name, the exception CX_SY_DYN_CALL_ILLEGAL_METHOD would be raised. The double also counts its calls, which is how
a test sees the indirect output of the object under test.
The test class ltcl_limit_check follows given, when, then. Its method setup creates a fresh object for every test.
CLASS lcl_limit_double DEFINITION FINAL FOR TESTING.
PUBLIC SECTION.
INTERFACES zif_exp_limit_source PARTIALLY IMPLEMENTED.
DATA calls TYPE i READ-ONLY.
METHODS constructor IMPORTING limit TYPE i.
PRIVATE SECTION.
DATA limit TYPE i.
ENDCLASS.
CLASS lcl_limit_double IMPLEMENTATION.
METHOD constructor.
me->limit = limit.
ENDMETHOD.
METHOD zif_exp_limit_source~get_limit.
calls = calls + 1.
limit = me->limit.
ENDMETHOD.
ENDCLASS.
CLASS ltcl_limit_check DEFINITION FINAL FOR TESTING DURATION SHORT RISK LEVEL HARMLESS.
PRIVATE SECTION.
DATA limit_double TYPE REF TO lcl_limit_double.
DATA cut TYPE REF TO zcl_exp_claim_limit_check.
METHODS setup.
METHODS accepts_amount_below_limit FOR TESTING RAISING cx_static_check.
METHODS accepts_amount_equal_to_limit FOR TESTING RAISING cx_static_check.
METHODS rejects_amount_above_limit FOR TESTING.
METHODS asks_for_the_limit_once FOR TESTING RAISING cx_static_check.
ENDCLASS.
CLASS ltcl_limit_check IMPLEMENTATION.
METHOD setup.
limit_double = NEW #( 500 ).
cut = NEW zcl_exp_claim_limit_check( limit_double ).
ENDMETHOD.
METHOD accepts_amount_below_limit.
cut->check( 499 ).
ENDMETHOD.
METHOD accepts_amount_equal_to_limit.
cut->check( 500 ).
ENDMETHOD.
METHOD rejects_amount_above_limit.
TRY.
cut->check( 501 ).
cl_abap_unit_assert=>fail( msg = 'limit exceeded was expected' ).
CATCH zcx_exp_limit_exceeded INTO DATA(error).
cl_abap_unit_assert=>assert_equals( act = error->limit exp = 500 msg = 'limit kept in the exception' ).
ENDTRY.
ENDMETHOD.
METHOD asks_for_the_limit_once.
cut->check( 100 ).
cl_abap_unit_assert=>assert_equals( act = limit_double->calls exp = 1 ).
ENDMETHOD.
ENDCLASS.
Source: ABAP Keyword Documentation: INTERFACES, PARTIALLY IMPLEMENTED and SAP-samples ABAP cheat sheets: ABAP Unit Tests
Three details of the listing are worth noticing. The tests for 499 and 500 call check and make no assertion: they pass
as long as no exception arrives, and the declaration RAISING cx_static_check lets a failing call end the test with the
exception, which ABAP Unit reports as an error. The test for 501 is the pattern for an expected exception: the
fail in the TRY block is reached only if the exception is missing, and the CATCH block checks what the
exception carries. The pair of tests at 500 and 501 pins the boundary, which is where such rules are usually wrong.
The playground starts the test classes of every global class and prints one line for each test method that it runs. It
prints nothing else when all tests pass, and it ends with exit code 0 (the command npm test of the lab). This is the
output of the whole lab project, which holds the tests of this page and the greeter class that ships with the lab.
ZCL_EXP_CLAIM_COUNTER: running ltcl_claim_counter->counts_only_approved_claims ZCL_EXP_CLAIM_COUNTER: running ltcl_claim_counter->counts_zero_without_data ZCL_EXP_CLAIM_LIMIT_CHECK: running ltcl_limit_check->accepts_amount_below_limit ZCL_EXP_CLAIM_LIMIT_CHECK: running ltcl_limit_check->accepts_amount_equal_to_limit ZCL_EXP_CLAIM_LIMIT_CHECK: running ltcl_limit_check->rejects_amount_above_limit ZCL_EXP_CLAIM_LIMIT_CHECK: running ltcl_limit_check->asks_for_the_limit_once ZCL_EXP_CLAIM_LIMIT_CHECK: running ltcl_limit_check_framework->accepts_amount_below_limit ZCL_EXP_CLAIM_LIMIT_CHECK: running ltcl_limit_check_framework->rejects_amount_above_limit ZCL_GREETER: running ltcl_greeter->greets_by_name
A test earns its place when it can fail. Changing the production code to amount >= limit, a typical off-by-one mistake,
and running the lab again stops at the boundary test with exit code 1. The playground prints the exception that the test
let through, here shortened to the first lines (the folder path is replaced by dots).
ZCL_EXP_CLAIM_LIMIT_CHECK: running ltcl_limit_check->accepts_amount_equal_to_limit
<ref *1> zcx_exp_limit_exceeded [Error]
at zcl_exp_claim_limit_check.check (file:///.../output/project/zcl_exp_claim_limit_check.clas.mjs:36:138)
at async #accepts_amount_equal_to_limit (file:///.../output/project/zcl_exp_claim_limit_check.clas.testclasses.mjs:84:5)
In an SAP system the same failure appears in the ABAP Unit result list with the test method name and a failure trace, and the other tests of the run still execute; the playground stops at the first failure.
The ABAP Test Double Framework
Writing a double class by hand costs a class per dependency. The ABAP Test Double Framework generates the double for you.
You call three static methods of the class CL_ABAP_TESTDOUBLE: create builds the double for an interface or a class,
configure_call says what a method call returns, and verify_expectations checks the interactions after the test. The
framework can configure the values of returning, exporting and changing parameters, exceptions and events for every
call, and it can verify, for example, how many times a method was called with given input.
CLASS ltcl_limit_check_framework DEFINITION FINAL FOR TESTING DURATION SHORT RISK LEVEL HARMLESS.
PRIVATE SECTION.
DATA cut TYPE REF TO zcl_exp_claim_limit_check.
METHODS setup.
METHODS accepts_amount_below_limit FOR TESTING RAISING cx_static_check.
METHODS rejects_amount_above_limit FOR TESTING.
ENDCLASS.
CLASS ltcl_limit_check_framework IMPLEMENTATION.
METHOD setup.
DATA(limit_source) = CAST zif_exp_limit_source( cl_abap_testdouble=>create( 'ZIF_EXP_LIMIT_SOURCE' ) ).
cl_abap_testdouble=>configure_call( limit_source )->returning( 500 ).
limit_source->get_limit( ).
cut = NEW zcl_exp_claim_limit_check( limit_source ).
ENDMETHOD.
METHOD accepts_amount_below_limit.
cut->check( 499 ).
ENDMETHOD.
METHOD rejects_amount_above_limit.
TRY.
cut->check( 501 ).
cl_abap_unit_assert=>fail( msg = 'limit exceeded was expected' ).
CATCH zcx_exp_limit_exceeded INTO DATA(error).
cl_abap_unit_assert=>assert_equals( act = error->limit exp = 500 ).
ENDTRY.
ENDMETHOD.
ENDCLASS.
Source: SAP-samples ABAP cheat sheets: ABAP Unit Tests and ABAP Platform: ABAP OO Test Double Framework
The method setup shows the framework pattern: create the double, then write the call that is configured, on the
double itself, directly after configure_call (here the call is limit_source->get_limit( )). From then on get_limit
returns 500. This listing is part of the lab project and ran together with the other listings, as the last two lines
before the greeter in the output above show; the playground has a community re-implementation of CL_ABAP_TESTDOUBLE,
so the verification with verify_expectations is not used here and is not claimed to work there.
The framework has limits that SAP lists. It creates doubles for global interfaces and for global classes. It does not
support local interfaces and local classes, classic exceptions, classes that are FINAL or FOR TESTING, classes with
CREATE PRIVATE, and classes whose constructor has mandatory parameters or can raise an exception. It cannot configure
methods that are FINAL, STATIC or PRIVATE. For a final or local class, use an interface in front of it or write
the double by hand. If the object under test has no interface for its dependency but the class is not final, a test can
also inherit from the class and redefine its public and protected methods; private methods cannot be replaced this way.
Testing code that reads the database: the ABAP SQL Test Double Framework
A method that runs SELECT on a table gives a different answer in every system. The ABAP SQL Test Double Framework solves
this by redirecting the statement. You name the tables or views the code depends on; the framework creates a double
table for each, ABAP SQL then reads from and writes to the doubles, and the test fills them with the rows it needs. The
real table is untouched, so the risk level of the test can stay HARMLESS. The framework fits the fixture methods:
-
cl_osql_test_environment=>createmakes the doubles for the dependency list. Call it once per test class, inclass_setup. -
clear_doublesempties them. Call it insetup, so that every test starts with fresh data. -
insert_test_datafills a double with the rows of an internal table of the table’s type. -
destroyremoves the doubles. Call it inclass_teardown.
The class under test counts the approved claims of the example. The listing and the test below ran in the playground
against its reduced ZEXP_CLAIM: status A means approved, as on the page about CDS view entities, and R is rejected.
CLASS zcl_exp_claim_counter DEFINITION
PUBLIC
FINAL
CREATE PUBLIC.
PUBLIC SECTION.
METHODS count_approved
RETURNING VALUE(count) TYPE i.
ENDCLASS.
CLASS zcl_exp_claim_counter IMPLEMENTATION.
METHOD count_approved.
SELECT COUNT(*) FROM zexp_claim WHERE status = 'A' INTO @count.
ENDMETHOD.
ENDCLASS.
CLASS ltcl_claim_counter DEFINITION FINAL FOR TESTING DURATION SHORT RISK LEVEL HARMLESS.
PRIVATE SECTION.
CLASS-DATA environment TYPE REF TO if_osql_test_environment.
CLASS-METHODS class_setup.
CLASS-METHODS class_teardown.
METHODS setup.
METHODS counts_only_approved_claims FOR TESTING.
METHODS counts_zero_without_data FOR TESTING.
ENDCLASS.
CLASS ltcl_claim_counter IMPLEMENTATION.
METHOD class_setup.
environment = cl_osql_test_environment=>create( i_dependency_list = VALUE #( ( 'ZEXP_CLAIM' ) ) ).
ENDMETHOD.
METHOD class_teardown.
environment->destroy( ).
ENDMETHOD.
METHOD setup.
environment->clear_doubles( ).
ENDMETHOD.
METHOD counts_only_approved_claims.
DATA claims TYPE STANDARD TABLE OF zexp_claim WITH EMPTY KEY.
claims = VALUE #( ( claim_id = 'C1' status = 'A' amount = 100 )
( claim_id = 'C2' status = 'A' amount = 250 )
( claim_id = 'C3' status = 'R' amount = 40 ) ).
environment->insert_test_data( claims ).
DATA(cut) = NEW zcl_exp_claim_counter( ).
cl_abap_unit_assert=>assert_equals( act = cut->count_approved( ) exp = 2 ).
ENDMETHOD.
METHOD counts_zero_without_data.
DATA(cut) = NEW zcl_exp_claim_counter( ).
cl_abap_unit_assert=>assert_equals( act = cut->count_approved( ) exp = 0 ).
ENDMETHOD.
ENDCLASS.
Both tests passed in the run shown above (the first two output lines). With the full table ZEXP_CLAIM of the running
example (with the client column, EMPLOYEE_ID, CURRENCY_CODE, TOTAL_AMOUNT and the audit include), the test is the same;
only the rows are built with those field names, and the run requires an SAP system, not run here.
More rules from the SAP page: you must supply proper values for the key fields of the table, or the framework can raise
an exception. If the dependency is a CDS view with parameters, the test supplies the parameter values together with the
data. The framework can insert explicit NULL values. If the dependency is a table, both read and write accesses are
redirected to the double. Access control of a CDS view that is read in the test is switched off while tests run. SAP
states that this framework has been available since back-end version SAP NetWeaver AS for ABAP 7.52. An older service,
the class CL_OSQL_REPLACE, redirects ABAP SQL accesses to other database objects in tests; for new tests prefer the
test double framework.
Testing CDS views: the CDS Test Double Framework
The logic of a CDS view entity, such as the case expression of ZI_ExpClaim that classifies a claim as large from 1000
upwards, can be tested without any database rows by the CDS Test Double Framework. It builds doubles for the first-level
dependencies of the view, here the table ZEXP_CLAIM, so the test inserts claims and then reads the view with an
ordinary SELECT. The framework gives read access to the view; to test code that also writes, use the ABAP SQL Test
Double Framework. Passing test_associations = 'X' to create also creates doubles for the first-level associations
of the view. When ABAP SQL code and CDS views read the same table, SAP recommends the CDS framework with
enable_double_redirection, because the ABAP SQL framework alone redirects only the statements and leaves the view
reading the real table.
CLASS ltcl_zi_expclaim DEFINITION FINAL FOR TESTING DURATION SHORT RISK LEVEL HARMLESS.
PRIVATE SECTION.
CLASS-DATA cds_env TYPE REF TO if_cds_test_environment.
CLASS-METHODS class_setup.
CLASS-METHODS class_teardown.
METHODS setup.
METHODS classifies_by_total_amount FOR TESTING.
ENDCLASS.
CLASS ltcl_zi_expclaim IMPLEMENTATION.
METHOD class_setup.
cds_env = cl_cds_test_environment=>create( i_for_entity = 'ZI_ExpClaim' ).
ENDMETHOD.
METHOD class_teardown.
cds_env->destroy( ).
ENDMETHOD.
METHOD setup.
cds_env->clear_doubles( ).
ENDMETHOD.
METHOD classifies_by_total_amount.
DATA claims TYPE STANDARD TABLE OF zexp_claim WITH EMPTY KEY.
claims = VALUE #( ( claim_id = 'C-1001' total_amount = '1500.00' )
( claim_id = 'C-1002' total_amount = '20.00' ) ).
cds_env->insert_test_data( i_data = claims ).
SELECT ClaimId, SizeClass FROM zi_expclaim ORDER BY ClaimId INTO TABLE @DATA(rows).
cl_abap_unit_assert=>assert_equals( act = rows[ 1 ]-sizeclass exp = 'large' ).
cl_abap_unit_assert=>assert_equals( act = rows[ 2 ]-sizeclass exp = 'small' ).
ENDMETHOD.
ENDCLASS.
Source: ABAP Platform: Writing Unit Test for a CDS Entity, ABAP Platform: ABAP SQL TDF and CDS TDF and SAP-samples ABAP cheat sheets: ABAP Unit Tests. The class name ltcl_zi_expclaim and the test data are invented for this page. This listing requires an SAP system; not run here.
Testing code that uses a RAP business object
Code that reads or changes a RAP business object through EML (see the page on EML) depends on that business object.
Calling the real one would run its behavior, determinations and database access. SAP offers two ways to replace it. The
older way is a hand-made class that implements the interface IF_ABAP_BEHAVIOR_TESTDOUBLE; SAP notes that this becomes a
burden when many business objects have to be replaced. The business object test double framework has two variants.
-
Transactional buffer double support, created with
CL_BOTD_TXBUFDBL_BO_TEST_ENV. SAP shows it in the demo test classltcl_txbufdbl_variant_demosof the ABAP Flight Reference Scenario. -
Mock EML API support, created with
CL_BOTD_MOCKEMLAPI_BO_TEST_ENV: the test configures what an EML call returns for a given input, and can verify afterwards that the call happened.
The listing shows the mock EML variant in the way the SAP cheat sheet uses it, adapted to the entity of this page’s
running example. The fixture creates the environment for the business object in class_setup, clear_doubles runs in
setup, and a test asks the environment for the double of the business object and configures a call.
CLASS ltcl_claim_eml DEFINITION FINAL FOR TESTING DURATION SHORT RISK LEVEL HARMLESS.
PRIVATE SECTION.
CLASS-DATA eml_env TYPE REF TO if_botd_mockemlapi_bo_test_env.
CLASS-METHODS class_setup.
CLASS-METHODS class_teardown.
METHODS setup.
ENDCLASS.
CLASS ltcl_claim_eml IMPLEMENTATION.
METHOD class_setup.
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 #( ( 'ZI_ExpClaim' ) ) ) ).
ENDMETHOD.
METHOD setup.
eml_env->clear_doubles( ).
ENDMETHOD.
METHOD class_teardown.
eml_env->destroy( ).
ENDMETHOD.
ENDCLASS.
Source: ABAP Platform: Managing Dependencies on RAP Business Objects with ABAP Unit and SAP-samples ABAP cheat sheets: ABAP Unit Tests. This listing requires an SAP system; not run here.
In a test method the double is then fetched with eml_env->get_test_double( 'ZI_ExpClaim' ), configured with a call
chain of the form configure_call( )->for_read( )->when_input( input )->then_set_output( output ), and checked with
verify( )->read( input )->is_called_times( times = 1 ). The input and output objects come from builder classes of the
framework; the SAP page and the demo class /DMO/TC_BOTD_TRAVEL_M_DEMOS of the ABAP Flight Reference Scenario show them
in full. The two variants and their rules are described on the SAP page cited below; the page about RAP business object tests and EML explains the business objects themselves.
Test seams for code that was not built for testing
The techniques above need a seam in the design: an interface, a constructor parameter, a table that the SQL framework can
redirect. Old code often has none. For it ABAP offers test seams, two statement pairs that exist only for tests.
TEST-SEAM name and END-TEST-SEAM mark a piece of production code as replaceable. TEST-INJECTION name and
END-TEST-INJECTION, written in a test class of the same program, replace its statements during a test. In production
nothing is replaced and the original statements run. The Keyword Documentation names the typical uses: authorization
checks, reading persistent data, modifying persistent data and creating test doubles.
TEST-SEAM authorization_seam.
AUTHORITY-CHECK OBJECT 'S_CTS_ADMI'
ID 'CTS_ADMFCT' FIELD 'TABL'.
END-TEST-SEAM.
IF sy-subrc = 0.
is_authorized = abap_true.
ENDIF.
TEST-INJECTION authorization_seam.
sy-subrc = 0.
END-TEST-INJECTION.
Source: ABAP Keyword Documentation: Test Seams. The first listing is production code, the second belongs in a test method or in setup. This listing requires an SAP system; not run here.
The same documentation says test seams are intended mainly for legacy code that, because of weak separation of concerns, is not suitable for unit tests, and that new programs should be structured so that seams are not needed. Prefer an interface and constructor injection in new code. Injections can only be written in test classes that are in a test include, and when the same seam gets several injections the last one wins.
Running the tests
In ADT, open the class and press Ctrl+Shift+F10 to run all its tests, or choose Run As > ABAP Unit Test from the
context menu. To run one test class or one test method, put the cursor on its name first. The result appears in the ABAP
Unit view, and the Failure Trace section shows what went wrong. For coverage press Ctrl+Shift+F11, or choose Run As >
ABAP Unit Test With… and select Coverage; the ABAP Coverage view then shows which lines the tests ran. ABAP Unit
tests can also be run by the ABAP Test Cockpit; see
ABAP Test Cockpit (ATC).
In classic tools, the Keyword Documentation for Standard ABAP names the ABAP Unit Browser of the ABAP Workbench for larger test runs. The coverage of tests ties in with the Coverage Analyzer. These are classic Standard ABAP tools; the ABAP Cloud side uses ADT and ATC.
What older books show, and what has changed
Complete ABAP (SAP PRESS, first edition 2016) teaches ABAP Unit in its chapter on test and analysis tools, and its
core is still right: separate the dependencies of the program into classes, replace them with mock objects, write a test
class with FOR TESTING, RISK LEVEL and DURATION, prepare the situation in setup and clean up in teardown, and
check with CL_ABAP_UNIT_ASSERT. The book builds every mock object by inheriting the real class and redefining its
methods. That still works for classes that are not final, but it is only one of the techniques today. The book does not
show the generated doubles of CL_ABAP_TESTDOUBLE, the SQL and CDS test double frameworks, the test double frameworks
for RAP business objects, the static fixture methods class_setup and class_teardown, or test seams, and its way to
run the tests is the menu of the ABAP Workbench (Program, Execute, Unit Tests) rather than ADT. It also describes
the durations as short under a minute, medium from one to five minutes and long up to an hour; the current Keyword
Documentation describes the expected time as a few seconds, around a minute and more than a minute, and lets the
administration set the limits. Write new tests with the current forms on this page and read the book for the idea of
isolating the code under test.
Common mistakes
-
Letting the class under test create its dependencies itself with
NEWinside its methods. There is then nothing to inject. Receive the dependency in the constructor and keep it behind an interface. -
Forgetting
RISK LEVELandDURATION. The default risk level isCRITICAL, and a test above the level that the administration allows is not run at all. -
Tests that depend on each other or on the order of the test methods. Prepare the whole situation in
setup, because it runs before every test. -
Not cleaning up the double tables. Without
clear_doublesinsetup, rows of one test stay visible in the next. -
A catch block without a
failin theTRYblock. If no exception is raised, the test passes even though it should have failed. -
Testing private methods directly. Test the public behavior; make the test class a friend only when a private attribute must be read or replaced.
-
Using test seams in new code. They are a way into legacy code, and the documentation recommends a structure that does not need them.
Summary
-
ABAP Unit runs test methods of classes marked
FOR TESTING; the source of a test class is not part of the production code and is not generated in production systems. -
A test has a given, a when and a then part; the then part uses the static methods of
CL_ABAP_UNIT_ASSERT, and the methodssetup,teardown,class_setupandclass_teardownform the fixture. -
RISK LEVELsays what a test may change andDURATIONhow long it is expected to take; tests above the allowed level do not run. -
A test double replaces a depended-on component. Give the class under test an interface and inject the double, for example through the constructor.
-
A double is a hand-made class, often with
PARTIALLY IMPLEMENTED, or generated withCL_ABAP_TESTDOUBLE. Database tables useCL_OSQL_TEST_ENVIRONMENT, CDS view entitiesCL_CDS_TEST_ENVIRONMENT, and RAP business objects their own test double frameworks. -
Test seams replace single statements in legacy code and are not meant for new code.
-
The local playground ran the hand-made double, the framework double and the SQL test environment; the CDS and RAP frameworks and test seams require an SAP system.
Try it
To do this by hand, follow the guide Write ABAP Unit Tests: it writes a local test class, makes a test fail and then fixes it.