0% found this document useful (0 votes)
25 views

Comp273 Exercises

This document provides exercises and solutions for test-driven ABAP development using tools like the ABAP Code Inspector, ABAP Unit, and ABAP Unit Browser. The exercises demonstrate how to write and execute unit tests with ABAP Unit, measure test coverage with the ABAP Unit Browser, and perform static code analysis with the Code Inspector. Completing the exercises helps ensure code is thoroughly tested and bug-free.

Uploaded by

Сергей З.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Comp273 Exercises

This document provides exercises and solutions for test-driven ABAP development using tools like the ABAP Code Inspector, ABAP Unit, and ABAP Unit Browser. The exercises demonstrate how to write and execute unit tests with ABAP Unit, measure test coverage with the ABAP Unit Browser, and perform static code analysis with the Code Inspector. Completing the exercises helps ensure code is thoroughly tested and bug-free.

Uploaded by

Сергей З.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

TEST DRIVEN AND BULLETPROOF ABAP

DEVELOPMENT
COMP273

Exercises / Solutions
Stefan Bresch / SAP AG
Thomas Ritter / SAP AG
2

Boost the quality of your software by learning how to do test driven development in ABAP using
ABAP Unit. Then, don't just hope that you have tested the essential parts of your software, but
measure the quality of your test coverage with the ABAP Coverage Analyzer. Find all potential
bugs in your software by taking advantage of the static analysis capabilities of the code inspector.
Additionally, the session will demonstrate proven techniques for bullet-proof error handling using
advanced exception concepts and ASSERT techniques. The session also contains numerous live
demos and exercises which will make it almost impossible for you to deliver bugs in your next
software project.

Contents

TOPIC Page

Static test tools – Code Inspector Introduction to static code analysis with the Code Inspector

Dynamic tests – ABAP Unit I Introduction into writing unit tests with ABAP Unit

Dynamic tests – ABAP Unit II More advanced ABAP Unit concepts

Dynamic tests – ABAP Unit Introduction into measuring the code coverage of unit tests by using the ABAP
Browser Unit Browser

Robust code – Exceptions I Introduction to creating and handling class based exceptions

Robust code – Exceptions II More advanced exception concepts including resumable exceptions
3

Exercise 1 – Code Inspector


Overview

Learn how to use the Code Inspector for performing static code analysis. This includes the creation of check variants,
the creation of program variants, the creation of inspections and the execution and analysis of inspections.

Exercise description

„ Use the code inspector to run the extended program check or syntax
check for all our test programs.
They start all with ZTSTECHED*

Exercise solution

1. Call transaction SCI.


2. Create a local check variant, e.g. ZTESTSET<counter>.
Switch on Extended program check in the folder.
‘Syntax Check /Generation’.
Save the variant.
3. Create a local program set, e.g. ZPRGSET<counter>.
In the Area ‘Object selection’ choose the tab ‘Class, Func Groups’ and then fill the field Program = ztsteched*.
Press save.
4. Create a local inspection e.g. ZINSPEC<number>
Specify the program set ZPRGSET<counter> and the check variant ZTESTSET<counter>.
Save the inspection.
Run the inspection in dialog or in background.
(Menu: Inspection->Execute)
5. If the green light aside to your inspection name appears, then the run has finished and you can display the results:
Menu: Inspection -> Results
4

Exercise 2 – ABAP Unit I


Overview

Learn how to create and execute local test classes. Find out how to write test methods by using the build-in assert
methods. See what happens if tests fail and discover how you can use the ABAP Unit result display to find out more
about the reasons why a particular test failed.

Exercise description

1. Open the transaction SE80.


2. Create a new report with the name ZTBEXERCISE2_<counter> without a top-include.
3. Create your first local test class by using the following template:

class ltcl_calculator_tests definition for testing duration short risk level harmless.
private section.
methods: divide_successful for testing.
endclass.

class ltcl_calculator_tests implementation.


method divide_successful.
endmethod.
endclass.

4. Add a method DIVIDE to the local test class which receives two integer numbers as parameters, divides them and
returns the result. The definition of the method looks like this: DIVIDE importing PARAM1 type i PARAM2 type i
returning value(result) type i.
5. Write a test which checks the result of the DIVIDE method. Use the static method
CL_AUNIT_ASSERT=>ASSERT_EQUALS() for checking whether your test is successful or not.
6. Execute your test by using the menu “Program Æ Test Æ UnitTest” or use the keyboard shortcut: Shift + Strg +
F10.
7. Get a feeling for the result display by causing your unit test to fail.
8. Once you are finished try to add more tests. What happens if you try to divide a number by zero?
5

Exercise solution

See program ZTBEXERCISE2_SOLUTION

Source code

report ztbexercise2_solution.

class ltcl_calculator_tests definition for testing duration short risk level harmless.
private section.
methods: divide_successful for testing,
divide importing number1 type i
number2 type i
returning value(result) type i.
endclass. "ltcl_calculator_tests DEFINITION

class ltcl_calculator_tests implementation.


method divide_successful.
data: result type i.
*Call the divide method and save result
result = me->divide( number1 = 4 number2 = 2 ).
*Make sure the result is correct by using one of the assert methods
*offered by the framework
cl_aunit_assert=>assert_equals( exp = 2 act = result ).
endmethod. "divide_successful

method divide.
*Simplest possible implementation
result = number1 / number2.
endmethod. "divide
endclass. "ltcl_calculator_tests IMPLEMENTATION
6

Exercise 3 – ABAP Unit II


Overview

Find out how to write fixtures for unit tests by using the build-in SETUP method. Use the most important assert
methods in a simple example scenario.

Exercise description

1. Open the transaction SE80.


2. Create a new report ZTBEXERCISE3_<counter> without a top-include.
3. Create a new test class with the name LTCL_STACK_TESTS.
4. Add a private attribute to the test class Æ data: stack type ref to ZCL_STACK.
5. Implement the SETUP method which instantiates the stack attribute.
6. Write a test for the POP and PUSH method of the stack class. Use the method ASSERT_EQUALS to make sure
that the right results get returned. What happens if you call POP on an empty stack?
7. Write a test for the method SIZE.
7

Exercise solution

See program ZTBEXERCISE3_SOLUTION

Source code

report ztbexercise3_solution.

class ltcl_stack_tests definition for testing risk level harmless duration short.
private section.
methods: setup,
push_pop_successful for testing,
pop_fail for testing,
size_successful for testing.

data: stack type ref to zcl_stack.


endclass. "ltcl_stack_tests DEFINITION

class ltcl_stack_tests implementation.


method setup.
"All tests operate on the stack object since we do not want to repeat ourselves
"and want to isolate our tests we create a fresh instance for each test method
create object me->stack.
endmethod. "setup

method push_pop_successful.
data: first_value type string value 'first_value',
second_value type string value 'second_value',
act_value type string.
"Add two values to the stack
me->stack->push( first_value ).
me->stack->push( second_value ).
"Make sure that the stack returns them in the correct order
act_value = me->stack->pop( ).
cl_aunit_assert=>assert_equals( exp = second_value act = act_value ).

act_value = me->stack->pop( ).
cl_aunit_assert=>assert_equals( exp = first_value act = act_value ).

endmethod. "PUSH_POP_SUCCESSFUL

method pop_fail.
data: act_value type string.
"Call pop on an empty stack. We expect that the method returns an empty value
act_value = me->stack->pop( ).
cl_aunit_assert=>assert_initial( act_value ).
endmethod. "POP_FAIL
8

method size_successful.
"Add three items to the stack
me->stack->push( 'first' ).
me->stack->push( 'second' ).
me->stack->push( 'third' ).
"Make sure the get_size method returns the correct value
cl_aunit_assert=>assert_equals( exp = 3 act = me->stack->get_size( ) ).
endmethod. "SIZE_SUCCESSFUL
endclass. "LTCL_STACK_TESTS IMPLEMENTATION
9

Exercise 4 – ABAP Unit Browser


Overview

Learn how you can use the ABAP Unit Browser to execute a set of unit tests and analyse the code coverage they
produce.

Exercise description

1. Open the transaction SE80.


2. Select the ABAP Unit Browser (If the tool is not display in the workbench add it via the menu: Utilities Æ Settings…
Æ Under tab “Workbench (General)” tick the checkbox “ABAP Unit Test Browser”).
3. Select “Favorite” in the dropdownlist and enter your username in the inputfield.
4. Create a new favorite.
5. Add the reports created during exercise 2 and 3 to the favorite.
6. Tick the checkbox “With Coverage Measurement” under extended measurement.
7. Execute the unit tests.
8. Analyze the code coverage which your test methods produce.
9. Optional: Execute your tests by using the Code Inspector.
10

Exercise solution

1. Select the ABAP Unit Browser (If the tool is not display in the workbench add it via the menu: Utilities Æ Settings…
Æ Under tab “Workbench (General)” tick the checkbox “ABAP Unit Test Browser”).

2. Select “Favorite” in the dropdownlist.


3. Create a new favorite.
11

4. Add the reports created during exercise 2 and 3 to the favorite.

5. Tick the checkbox “With Coverage Measurement” under extended measurement.


12

6. Execute the unit tests.

7. Analyze the code coverage which your test methods produce.


13

Exercise 5 – Exceptions I
Overview

Learn how to catch exceptions by using the TRY … CATCH … ENDTRY syntax. Find out how to specify the exception
you want to catch. See how ABAP Unit handles uncaught exceptions and how to write unit tests for exception handling.
Get a better feeling how the program flow changes when you use exceptions by debugging the result of the exercise.

Exercise description

1. Open the transaction SE80.


2. Create a new report ZTBEXERCISE5_<counter> without a top-include.
3. Create a new test class with the name LTCL_EXCEPTIONS_TESTS.
4. Create a new test method with the name RAISE_EXCEPTION.
5. Provoke the exception CX_SY_ZERODIVIDE by trying to divide a number by zero.
6. Have a look at how ABAP Unit automatically catches exceptions.
7. Now, write a test which makes sure that a) the system throws an exception when you try to divide a number by
zero b) the system throws the exception CX_SY_ZERODIVIDE. One hint the method
CL_AUNIT_ASSERT=>FAIL() should be used in the test method. Use the optional into clause to save the
exception object into a variable.
8. Use the debugger to see how the code gets executed.
14

Exercise solution

See program ZTBEXERCISE5_SOLUTION

Source code

report ztbexercise5_solution.

class ltcl_exceptions_tests definition for testing risk level harmless duration short.
private section.
methods: raise_exception for testing.
endclass. "ltcl_exceptions_tests DEFINITION

class ltcl_exceptions_tests implementation.


method raise_exception.
data: result type i,
exception type ref to cx_sy_zerodivide.

try.
*Divide by zero causes the exception cx_sy_zerodivide
result = 1 / 0.
*fail causes the test to fail if the exception would not occur
cl_aunit_assert=>fail( 'No exception thrown by 1 / 0!' ).
catch cx_sy_zerodivide into exception.
*The block is expected to get executed
cl_aunit_assert=>assert_bound( exception ).
catch cx_root.
*We expect the exception cx_sy-zerodivide any other exception is a bug
cl_aunit_assert=>fail( 'Unexpected exception occured!' ).
endtry.
endmethod. "raise_exception
endclass. "ltcl_exceptions_tests IMPLEMENTATION
15

Exercise 6 – Exceptions II
Overview

Learn about more advanced exception concepts by using resumable exceptions and the retry statement in a simple
example scenario. See how you can use message classes in order to define exception texts.

Exercise description

1. Open the transaction SE80.


2. Create a new report ZTBEXERCISE6_<counter> without a top-include.
3. Open the report ZTBEXERCISE6_BASE and copy the local test class LTCL_ADV_EXCEPTIONS_TESTS into the
newly created report.
4. Have a look at the class ZCL_FILESYSTEM which is a very simple fake implementation of a file system. Find out
what exceptions the method ADD_FILE might throw.
5. Start implementing the test method RETRY_RESUME_EXCEPTION by creating an instance of the class
ZCL_FILESYSTEM.
6. Now, use the instance to add a new file to the file system. Make sure you catch all exceptions. The exception
ZCX_FILE_ALREADY_EXISTS is resumable so make sure you use the correct syntax for the catch block.
7. React appropriately to all exceptions. If there is no space on the file system left call the appropriate method to
empty the recycle bin and retry. If the file already exists overwrite it by resuming the method call.
8. In the end make sure by checking the return value of the method ADD_FILE that the file was successfully added to
the file system.
9. Debug your application and observe the program flow.
10. Optional: Have a look at the exception ZCX_FILE_ALREADY_EXISTS and find out how it uses a message class
+ a class attribute to generate the exception text.
16

Exercise solution

See program ZTBEXERCISE6_SOLUTION

Source code

report ztbexercise6_solution.

class ltcl_adv_exceptions_tests definition for testing risk level harmless duration sho
rt.
private section.
methods: retry_resume_exception for testing.
endclass. "ltcl_exceptions_tests DEFINITION

class ltcl_adv_exceptions_tests implementation.


method retry_resume_exception.
data: filesystem type ref to zcl_filesystem,
result type abap_bool.
*Create filesystem object
create object filesystem.

try.
*Try to add a file. The first call triggers zcx_no_space_left exception
result = filesystem->add_file( name = 'test.txt' content = 'test content' ).
*Make sure the method call was successful and the file was added
cl_aunit_assert=>assert_equals( exp = abap_true act = result ).
catch zcx_no_space_left.
*Filesystem is full. Lets clean up the recycling bin and retry
filesystem->empty_recycle_bin( ).
retry.
catch before unwind zcx_file_already_exists.
*The file already exists. We want to overwrite it and therefore resume the method call.
resume.
endtry.
endmethod. "raise_exception
endclass. "ltcl_exceptions_tests IMPLEMENTATION
17

Copyright 2007 SAP AG. All Rights Reserved


No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP
AG. The information contained herein may be changed without prior notice.
Some software products marketed by SAP AG and its distributors contain proprietary software components of other software
vendors.
Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation.
IBM, DB2, DB2 Universal Database, OS/2, Parallel Sysplex, MVS/ESA, AIX, S/390, AS/400, OS/390, OS/400, iSeries, pSeries,
xSeries, zSeries, System i, System i5, System p, System p5, System x, System z, System z9, z/OS, AFP, Intelligent Miner,
WebSphere, Netfinity, Tivoli, Informix, i5/OS, POWER, POWER5, POWER5+, OpenPower and PowerPC are trademarks or
registered trademarks of IBM Corporation.
Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either trademarks or registered trademarks of Adobe Systems
Incorporated in the United States and/or other countries.
Oracle is a registered trademark of Oracle Corporation.
UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group.
Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of
Citrix Systems, Inc.
HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts
Institute of Technology.
Java is a registered trademark of Sun Microsystems, Inc.
JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by
Netscape.
MaxDB is a trademark of MySQL AB, Sweden.
SAP, R/3, mySAP, mySAP.com, xApps, xApp, SAP NetWeaver, and other SAP products and services mentioned herein as well as
their respective logos are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the
world. All other product and service names mentioned are the trademarks of their respective companies. Data contained in this
document serves informational purposes only. National product specifications may vary.

The information in this document is proprietary to SAP. No part of this document may be reproduced, copied, or transmitted in any
form or for any purpose without the express prior written permission of SAP AG.
This document is a preliminary version and not subject to your license agreement or any other agreement with SAP. This document
contains only intended strategies, developments, and functionalities of the SAP® product and is not intended to be binding upon
SAP to any particular course of business, product strategy, and/or development. Please note that this document is subject to change
and may be changed by SAP at any time without notice.
SAP assumes no responsibility for errors or omissions in this document. SAP does not warrant the accuracy or scompleteness of the
information, text, graphics, links, or other items contained within this material. This document is provided without a warranty of any
kind, either express or implied, including but not limited to the implied warranties of merchantability, fitness for a particular purpose,
or non-infringement.
SAP shall have no liability for damages of any kind including without limitation direct, special, indirect, or consequential damages
that may result from the use of these materials. This limitation shall not apply in cases of intent or gross negligence.
The statutory liability for personal injury and defective products is not affected. SAP has no control over the information that you may
access through the use of hot links contained in these materials and does not endorse your use of third-party Web pages nor
provide any warranty whatsoever relating to third-party Web pages.

SAP assumes no responsibility for errors or omissions in these materials

You might also like