Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock sy-uname in ABAP Unit test

I am trying to write my first unit tests in ABAP.

My method under test fetches team members of the logged-on user (via system variable sy-uname).

Since I want the test to run for everyone I can't just let the method run and assert one of my own team members.

I want to mock sy-uname, so the test is not dependent on who is executing it.

Is this possible? If yes how do you mock system parameters?

like image 322
Erch Avatar asked Mar 04 '23 11:03

Erch


1 Answers

I half agree with the answers given by Haojie: one should not use Test Seams (exist since ABAP 7.50) for a so simple case (replacing sy-uname), you should only use a provider class as he proposed.

Test seams are considered like a pollution of the productive code, because it reduces the readability of the code (mix of productive and test code).

NB: the ABAP documentation of test seams (link above) gives at least the following possible usages:

  • Authorization checks (AUTHORITY-CHECK)
  • ABAP SQL statements (SELECT, MODIFY, etc.) - It became a bad example since ABAP SQL can be mocked with the ABAP 7.52 class CL_OSQL_TEST_ENVIRONMENT.

As a rule-of-thumb, test seams should not be used at all, or considered as a solution of very last resort.

BUT if there's no other choice, like adding tests to a "legacy" code (old-badly-written code, usually not written using object-oriented design patterns, that is considered not testable via ABAP Unit), then you may have eventually no other choice.

As stated by Horst Keller (one of best ABAP experts in the world and responsible of ABAP documentation at SAP):

"If you cannot redesign and rewrite the whole application, as a workaround you make the code test dependent. This is regarded as bad style, but it helps."

As the question is only about sy-uname and it's not about the whole program, so the effort to refactor sy-uname is much lesser, so there's no excuse to not using a class.

like image 134
Sandra Rossi Avatar answered Mar 12 '23 04:03

Sandra Rossi